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
1278C
1278
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>Карлсон недавно обнаружил огромные запасы ягодного варенья в подвале дома. Если точнее, то там оказались $$$2n$$$ банок клубничного и черничного варенья.</p><p>Все $$$2n$$$ банок расставлены в ряд. Лестница в подвал находится ровно в середине этого ряда. Поэтому, когда Карлсон спускается в подвал, он видит ровно $$$n$$$ банок слева и $$$n$$$ банок справа.</p><p>Например, подвал может выглядеть следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/4f787c551100d1f9286f9d2baeb99fd82a18fc73.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Карлсон — очень прямолинейный молодой человек, поэтому он сразу начинает есть варенье. За одну минуту он опустошает либо первую непустую банку слева, либо первую непустую банку справа.</p><p>Наконец, Карлсон решил, что в конце процесса должно остаться равное количество банок с клубничным и черничным вареньем.</p><p>Например, результат может быть таким:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e56bd1d3ca1b2e7825388a5cbb8b6148bb7700d6.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-style-it">Он съел $$$1$$$ банку слева, а затем $$$5$$$ банок справа.</span> <span class="tex-font-style-it">Осталось ровно по $$$3$$$ полных банки клубничного и черничного варенья.</span> </center><p>Банки пронумерованы от $$$1$$$ до $$$2n$$$ слева направо, так что Карлсон начинает между банками $$$n$$$ и $$$n+1$$$.</p><p>Какое минимальное число банок Карлсону придется опустошить, чтобы осталось равное количество банок с клубничным и черничным вареньем?</p><p>Вам нужно ответить на $$$t$$$ наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных записано одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$).</p><p>В второй строке каждого набора входных данных записаны $$$2n$$$ целых чисел $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ значит, что $$$i$$$-я банка слева — это банка клубничного варенья, а $$$a_i=2$$$ значит, что это банка черничного варенья.</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 6 1 1 1 2 2 1 2 1 2 1 1 2 2 1 2 1 2 3 1 1 1 1 1 1 2 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 0 6 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На картинке описывается первый набор входных данных.</p><p>Во втором наборе входных данных количества банок с клубничным и с черничным вареньем уже совпадают.</p><p>В третьем наборе входных данных Карлсону придется съесть все $$$6$$$ банок, так чтобы осталось $$$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="d9acb1823e19301ca0e462a6d73e29b1"/> <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="adb7f5bbc027c55fa2d7ec5b1056c392fc5e47d2"/> <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='d9acb1823e19301ca0e462a6d73e29b1'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1278%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='d9acb1823e19301ca0e462a6d73e29b1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1278">Educational Codeforces Round 78 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='d9acb1823e19301ca0e462a6d73e29b1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1278/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='d9acb1823e19301ca0e462a6d73e29b1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="498932"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d9acb1823e19301ca0e462a6d73e29b1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="498932"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72268" title="Educational Codeforces Round 78 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10105:10106" 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/72330" title="Разбор Educational Codeforces Round 78" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10133:10134" 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/1278">Задачи</a></li> <li><a href="/contest/1278/submit">Отослать</a></li> <li><a href="/contest/1278/my">Мои посылки</a></li> <li><a href="/contest/1278/status">Статус</a></li> <li><a href="/contest/1278/hacks">Взломы</a></li> <li><a href="/contest/1278/standings">Положение</a></li> <li><a href="/contest/1278/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8c23a315a596b7f28d7c5f2eca13bc8e7b5101e6"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Карлсон недавно обнаружил огромные запасы ягодного варенья в подвале дома. Если точнее, то там оказались $$$2n$$$ банок клубничного и черничного варенья.</p><p>Все $$$2n$$$ банок расставлены в ряд. Лестница в подвал находится ровно в середине этого ряда. Поэтому, когда Карлсон спускается в подвал, он видит ровно $$$n$$$ банок слева и $$$n$$$ банок справа.</p><p>Например, подвал может выглядеть следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/4f787c551100d1f9286f9d2baeb99fd82a18fc73.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Карлсон — очень прямолинейный молодой человек, поэтому он сразу начинает есть варенье. За одну минуту он опустошает либо первую непустую банку слева, либо первую непустую банку справа.</p><p>Наконец, Карлсон решил, что в конце процесса должно остаться равное количество банок с клубничным и черничным вареньем.</p><p>Например, результат может быть таким:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e56bd1d3ca1b2e7825388a5cbb8b6148bb7700d6.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-style-it">Он съел $$$1$$$ банку слева, а затем $$$5$$$ банок справа.</span> <span class="tex-font-style-it">Осталось ровно по $$$3$$$ полных банки клубничного и черничного варенья.</span> </center><p>Банки пронумерованы от $$$1$$$ до $$$2n$$$ слева направо, так что Карлсон начинает между банками $$$n$$$ и $$$n+1$$$.</p><p>Какое минимальное число банок Карлсону придется опустошить, чтобы осталось равное количество банок с клубничным и черничным вареньем?</p><p>Вам нужно ответить на $$$t$$$ наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных записано одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$).</p><p>В второй строке каждого набора входных данных записаны $$$2n$$$ целых чисел $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ значит, что $$$i$$$-я банка слева — это банка клубничного варенья, а $$$a_i=2$$$ значит, что это банка черничного варенья.</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 6 1 1 1 2 2 1 2 1 2 1 1 2 2 1 2 1 2 3 1 1 1 1 1 1 2 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 0 6 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На картинке описывается первый набор входных данных.</p><p>Во втором наборе входных данных количества банок с клубничным и с черничным вареньем уже совпадают.</p><p>В третьем наборе входных данных Карлсону придется съесть все $$$6$$$ банок, так чтобы осталось $$$0$$$ банок каждого варенья.</p><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:53: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:'812491c3fa4a76ad',t:'MTY5NjY2NTE5Ni43MTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1700"]
1278D
1278
D
ru
D. Дерево отрезков
<div class="problem-statement"><div class="header"><div class="title">D. Дерево отрезков</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Как видно из названия задачи, вам предстоит решить задачу про отрезки и деревья.</p><p>Напомним, что деревом является связный неориентированным граф, такой что между каждой парой его вершин существует ровно один простой путь.</p><p>Вам дано $$$n$$$ отрезков $$$[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]$$$, $$$l_i &lt; r_i$$$ для всех $$$i$$$. Гарантируется, что концы отрезков являются целыми числами, все концы являются уникальными — нет такой пары отрезков, которые начинались бы в одной и той же точке, заканчивались в одной и той же точке, или один бы начинался в такой точке, что другой в ней заканчивается.</p><p>Давайте построим граф с $$$n$$$ вершинами. Вершины $$$v$$$ и $$$u$$$ соединены ребром тогда и только тогда, когда отрезки $$$[l_v, r_v]$$$ и $$$[l_u, r_u]$$$ пересекаются и ни один из них не лежит полностью внутри другого.</p><p>Например, пары $$$([1, 3], [2, 4])$$$ и $$$([5, 10], [3, 7])$$$ будут образовывать ребра, а пары $$$([1, 2], [3, 4])$$$ и $$$([5, 7], [3, 10])$$$ не будут.</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>$$$i$$$-я из следующих $$$n$$$ строк содержит описание $$$i$$$ отрезка — два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i &lt; r_i \le 2n$$$).</p><p>Гарантируется, что концы всех отрезков попарно различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<span class="tex-font-style-tt">YES</span>», если полученный граф является деревом и «<span class="tex-font-style-tt">NO</span>» в противном случае.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 9 12 2 11 1 3 6 10 5 7 4 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 3 2 4 5 9 6 8 7 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 8 3 6 2 9 7 10 1 4 </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><p><img class="tex-graphics" src="https://espresso.codeforces.com/2d2aa7a63ebeae31d1149ddfab2d05bb06ed07e8.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Граф полученный во втором примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/8248c6ced1f83fdef9e4a4875fb02b297d359006.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Граф полученный в третьем примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/aaa130bc901103f6b135ddb68f60fc1b1c26049d.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="1a65d68b0254bbe6fea49fbe6b0737c4"/> <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="adb7f5bbc027c55fa2d7ec5b1056c392fc5e47d2"/> <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='1a65d68b0254bbe6fea49fbe6b0737c4'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1278%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='1a65d68b0254bbe6fea49fbe6b0737c4'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1278">Educational Codeforces Round 78 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='1a65d68b0254bbe6fea49fbe6b0737c4'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1278/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств"> снм </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='1a65d68b0254bbe6fea49fbe6b0737c4'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="498933"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1a65d68b0254bbe6fea49fbe6b0737c4'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="498933"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72268" title="Educational Codeforces Round 78 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10105:10106" 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/72330" title="Разбор Educational Codeforces Round 78" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10133:10134" 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/1278">Задачи</a></li> <li><a href="/contest/1278/submit">Отослать</a></li> <li><a href="/contest/1278/my">Мои посылки</a></li> <li><a href="/contest/1278/status">Статус</a></li> <li><a href="/contest/1278/hacks">Взломы</a></li> <li><a href="/contest/1278/standings">Положение</a></li> <li><a href="/contest/1278/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1534c01c6f653442549c4d2fbd2b14ff0ab36f8b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Дерево отрезков</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Как видно из названия задачи, вам предстоит решить задачу про отрезки и деревья.</p><p>Напомним, что деревом является связный неориентированным граф, такой что между каждой парой его вершин существует ровно один простой путь.</p><p>Вам дано $$$n$$$ отрезков $$$[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]$$$, $$$l_i &lt; r_i$$$ для всех $$$i$$$. Гарантируется, что концы отрезков являются целыми числами, все концы являются уникальными — нет такой пары отрезков, которые начинались бы в одной и той же точке, заканчивались в одной и той же точке, или один бы начинался в такой точке, что другой в ней заканчивается.</p><p>Давайте построим граф с $$$n$$$ вершинами. Вершины $$$v$$$ и $$$u$$$ соединены ребром тогда и только тогда, когда отрезки $$$[l_v, r_v]$$$ и $$$[l_u, r_u]$$$ пересекаются и ни один из них не лежит полностью внутри другого.</p><p>Например, пары $$$([1, 3], [2, 4])$$$ и $$$([5, 10], [3, 7])$$$ будут образовывать ребра, а пары $$$([1, 2], [3, 4])$$$ и $$$([5, 7], [3, 10])$$$ не будут.</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>$$$i$$$-я из следующих $$$n$$$ строк содержит описание $$$i$$$ отрезка — два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i &lt; r_i \le 2n$$$).</p><p>Гарантируется, что концы всех отрезков попарно различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<span class="tex-font-style-tt">YES</span>», если полученный граф является деревом и «<span class="tex-font-style-tt">NO</span>» в противном случае.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 9 12 2 11 1 3 6 10 5 7 4 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 3 2 4 5 9 6 8 7 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 8 3 6 2 9 7 10 1 4 </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><p><img class="tex-graphics" src="https://espresso.codeforces.com/2d2aa7a63ebeae31d1149ddfab2d05bb06ed07e8.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Граф полученный во втором примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/8248c6ced1f83fdef9e4a4875fb02b297d359006.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Граф полученный в третьем примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/aaa130bc901103f6b135ddb68f60fc1b1c26049d.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:53: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:'812491cf193d7b47',t:'MTY5NjY2NTE5OS43MjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0441\u043d\u043c", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2100"]
1278E
1278
E
ru
E. Тесты для задачи D
<div class="problem-statement"><div class="header"><div class="title">E. Тесты для задачи 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>Нам было очень сложно придумать тесты для задачи D. Чтобы подготовить сильные тесты, нам пришлось решить следующую задачу.</p><p>Для заданного неориентированного помеченного дерева, состоящего из $$$n$$$ вершин, найдите набор отрезков, такой что:</p><ol> <li> концы каждого отрезка являются целыми числами от $$$1$$$ до $$$2n$$$, и каждое целое число от $$$1$$$ до $$$2n$$$ должно встречаться как конец ровно одного отрезка; </li><li> все отрезки — невырожденные; </li><li> для каждой такой пары чисел $$$(i, j)$$$, что $$$i \ne j$$$, $$$i \in [1, n]$$$ и $$$j \in [1, n]$$$, вершины $$$i$$$ и $$$j$$$ соединены ребром тогда и только тогда, когда отрезки $$$i$$$ и $$$j$$$ пересекаются, но ни отрезок $$$i$$$ не содержится полностью в отрезке $$$j$$$, ни отрезок $$$j$$$ полностью не содержится в отрезке $$$i$$$. </li></ol><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 - 1$$$ строк содержат по два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), описывающие концы $$$i$$$-го ребра. </p><p>Гарантируется, что данный граф является деревом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ пар целых чисел, $$$i$$$-я пара должна содержать два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i &lt; r_i \le 2n$$$) — концы $$$i$$$-го отрезка. Все $$$2n$$$ целых чисел, которые вы вывели, должны быть различными.</p><p>Гарантируется, что ответ всегда существует.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 1 2 1 3 3 4 3 5 2 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 12 7 10 3 11 1 5 2 4 6 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="07ddd0f5557b77cf2d5c1b023a6bace6"/> <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="adb7f5bbc027c55fa2d7ec5b1056c392fc5e47d2"/> <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='07ddd0f5557b77cf2d5c1b023a6bace6'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1278%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='07ddd0f5557b77cf2d5c1b023a6bace6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1278">Educational Codeforces Round 78 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='07ddd0f5557b77cf2d5c1b023a6bace6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1278/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Разделяй и властвуй"> разделяй и властвуй </span> </div> <div class="roundbox borderTopRound 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='07ddd0f5557b77cf2d5c1b023a6bace6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="498934"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='07ddd0f5557b77cf2d5c1b023a6bace6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="498934"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72268" title="Educational Codeforces Round 78 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10105:10106" 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/72330" title="Разбор Educational Codeforces Round 78" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10133:10134" 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/1278">Задачи</a></li> <li><a href="/contest/1278/submit">Отослать</a></li> <li><a href="/contest/1278/my">Мои посылки</a></li> <li><a href="/contest/1278/status">Статус</a></li> <li><a href="/contest/1278/hacks">Взломы</a></li> <li><a href="/contest/1278/standings">Положение</a></li> <li><a href="/contest/1278/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7f9e67c2daad71090ef67f08ae67b5cb0b14f698"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Тесты для задачи 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>Нам было очень сложно придумать тесты для задачи D. Чтобы подготовить сильные тесты, нам пришлось решить следующую задачу.</p><p>Для заданного неориентированного помеченного дерева, состоящего из $$$n$$$ вершин, найдите набор отрезков, такой что:</p><ol> <li> концы каждого отрезка являются целыми числами от $$$1$$$ до $$$2n$$$, и каждое целое число от $$$1$$$ до $$$2n$$$ должно встречаться как конец ровно одного отрезка; </li><li> все отрезки — невырожденные; </li><li> для каждой такой пары чисел $$$(i, j)$$$, что $$$i \ne j$$$, $$$i \in [1, n]$$$ и $$$j \in [1, n]$$$, вершины $$$i$$$ и $$$j$$$ соединены ребром тогда и только тогда, когда отрезки $$$i$$$ и $$$j$$$ пересекаются, но ни отрезок $$$i$$$ не содержится полностью в отрезке $$$j$$$, ни отрезок $$$j$$$ полностью не содержится в отрезке $$$i$$$. </li></ol><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 - 1$$$ строк содержат по два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), описывающие концы $$$i$$$-го ребра. </p><p>Гарантируется, что данный граф является деревом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ пар целых чисел, $$$i$$$-я пара должна содержать два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i &lt; r_i \le 2n$$$) — концы $$$i$$$-го отрезка. Все $$$2n$$$ целых чисел, которые вы вывели, должны быть различными.</p><p>Гарантируется, что ответ всегда существует.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 1 2 1 3 3 4 3 5 2 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 12 7 10 3 11 1 5 2 4 6 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 </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:53:21</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'812491e1fec2169b',t:'MTY5NjY2NTIwMS4wNzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "*2200"]
1278F
1278
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>Рассмотрим следующий эксперимент. У вас есть колода из $$$m$$$ карт, ровно одна из них — джокер. $$$n$$$ раз вы производите следующие действия: перемешиваете колоду, берете верхнюю карту, просматриваете ее и возвращаете ее в колоду.</p><p>Пусть $$$x$$$ — количество раз, когда вы брали с вершины колоды джокера. Предполагая, что при каждом перемешивании колоды все $$$m!$$$ перестановок карт равновероятны, чему равно математическое ожидание $$$x^k$$$? Выведите ответ по модулю $$$998244353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке заданы три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$1 \le n, m &lt; 998244353$$$, $$$1 \le k \le 5000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — математическое ожидание $$$x^k$$$, взятое по модулю $$$998244353$$$ (ответ всегда можно представить в виде несократимой дроби $$$\frac{a}{b}$$$, где $$$b \mod 998244353 \ne 0$$$; выведите $$$a \cdot b^{-1} \mod 998244353$$$).</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 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 5000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 499122178 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 998244352 1337 5000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 326459680 </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="1e60e800e224622fbdc83d131de9d189"/> <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="adb7f5bbc027c55fa2d7ec5b1056c392fc5e47d2"/> <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='1e60e800e224622fbdc83d131de9d189'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1278%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='1e60e800e224622fbdc83d131de9d189'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1278">Educational Codeforces Round 78 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='1e60e800e224622fbdc83d131de9d189'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1278/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др."> теория вероятностей </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='1e60e800e224622fbdc83d131de9d189'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="498935"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1e60e800e224622fbdc83d131de9d189'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="498935"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72268" title="Educational Codeforces Round 78 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10105:10106" 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/72330" title="Разбор Educational Codeforces Round 78" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10133:10134" 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/1278">Задачи</a></li> <li><a href="/contest/1278/submit">Отослать</a></li> <li><a href="/contest/1278/my">Мои посылки</a></li> <li><a href="/contest/1278/status">Статус</a></li> <li><a href="/contest/1278/hacks">Взломы</a></li> <li><a href="/contest/1278/standings">Положение</a></li> <li><a href="/contest/1278/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b4e73d6c231a3272283fb136c3e0fd556b0bbe78"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Рассмотрим следующий эксперимент. У вас есть колода из $$$m$$$ карт, ровно одна из них — джокер. $$$n$$$ раз вы производите следующие действия: перемешиваете колоду, берете верхнюю карту, просматриваете ее и возвращаете ее в колоду.</p><p>Пусть $$$x$$$ — количество раз, когда вы брали с вершины колоды джокера. Предполагая, что при каждом перемешивании колоды все $$$m!$$$ перестановок карт равновероятны, чему равно математическое ожидание $$$x^k$$$? Выведите ответ по модулю $$$998244353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке заданы три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$1 \le n, m &lt; 998244353$$$, $$$1 \le k \le 5000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — математическое ожидание $$$x^k$$$, взятое по модулю $$$998244353$$$ (ответ всегда можно представить в виде несократимой дроби $$$\frac{a}{b}$$$, где $$$b \mod 998244353 \ne 0$$$; выведите $$$a \cdot b^{-1} \mod 998244353$$$).</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 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 5000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 499122178 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 998244352 1337 5000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 326459680 </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:53: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:'812491eacd6116f7',t:'MTY5NjY2NTIwMi40NTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\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.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2600"]
1279A
1279
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>Местный магазин в этом году начал предоставлять новую услугу, которая называется «Создай свою гирлянду». То есть можно купить красных, зеленых и синих лампочек, предоставить их, а сотрудники магазина спаяют из них одну гирлянду. В полученной гирлянде все лампочки будут расположены в один ряд. Более того, ни одна пара лампочек одного цвета не будут находиться рядом в этой гирлянде!</p><p>Например, если предоставить $$$3$$$ красных, $$$3$$$ зеленых и $$$3$$$ синих лампочки, то полученная гирлянда может выглядеть как «<span class="tex-font-style-tt">RGBRBGBGR</span>» («<span class="tex-font-style-tt">RGB</span>» — это красный, зеленый и синий цвет, соответственно). Обратите внимание, что лампы одного цвета могут быть на концах гирлянды.</p><p>Однако, если предоставить, например, $$$1$$$ красную, $$$10$$$ зеленых и $$$2$$$ синих лампочки, то сотрудники не смогут сделать из них гирлянду. Любая гирлянда, состоящая из этих лампочек будет содержать хотя бы одну пару лампочек одного цвета, находящуюся рядом друг с другом. Обратите внимание, что сотрудники должны использовать все лампочки, которые вы предоставите.</p><p>Так что Поликарп купил несколько наборов лампочек, и теперь интересуется, смогут ли сотрудники собрать гирлянду из каждого из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов лампочек, которые купил Поликарп.</p><p>В каждой из следующих $$$t$$$ строк записаны по три целых числа $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^9$$$) — количество красных, зеленых и синих лампочек, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк — для каждого набора лампочек выведите «<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> 3 3 3 3 1 10 2 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No Yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первые два набора описаны в условии.</p><p>В третьем наборе можно собрать гирлянду «<span class="tex-font-style-tt">RBRG</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="1bf0732d706bf9a47e4a95568d7fbf57"/> <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="3fd08d06ea3f0cde970e15e21c8ce523e24f62d3"/> <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='1bf0732d706bf9a47e4a95568d7fbf57'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1279%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='1bf0732d706bf9a47e4a95568d7fbf57'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1279">Educational Codeforces Round 79 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='1bf0732d706bf9a47e4a95568d7fbf57'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1279/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='1bf0732d706bf9a47e4a95568d7fbf57'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="504273"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1bf0732d706bf9a47e4a95568d7fbf57'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="504273"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72494" title="Educational Codeforces Round 79 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10179:10180" 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/72577" title="Разбор Educational Codeforces Round 79" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10201:10202" 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/1279">Задачи</a></li> <li><a href="/contest/1279/submit">Отослать</a></li> <li><a href="/contest/1279/my">Мои посылки</a></li> <li><a href="/contest/1279/status">Статус</a></li> <li><a href="/contest/1279/hacks">Взломы</a></li> <li><a href="/contest/1279/standings">Положение</a></li> <li><a href="/contest/1279/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_75765c371c03728386665e0e7e7e97a1b1d16dc3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Местный магазин в этом году начал предоставлять новую услугу, которая называется «Создай свою гирлянду». То есть можно купить красных, зеленых и синих лампочек, предоставить их, а сотрудники магазина спаяют из них одну гирлянду. В полученной гирлянде все лампочки будут расположены в один ряд. Более того, ни одна пара лампочек одного цвета не будут находиться рядом в этой гирлянде!</p><p>Например, если предоставить $$$3$$$ красных, $$$3$$$ зеленых и $$$3$$$ синих лампочки, то полученная гирлянда может выглядеть как «<span class="tex-font-style-tt">RGBRBGBGR</span>» («<span class="tex-font-style-tt">RGB</span>» — это красный, зеленый и синий цвет, соответственно). Обратите внимание, что лампы одного цвета могут быть на концах гирлянды.</p><p>Однако, если предоставить, например, $$$1$$$ красную, $$$10$$$ зеленых и $$$2$$$ синих лампочки, то сотрудники не смогут сделать из них гирлянду. Любая гирлянда, состоящая из этих лампочек будет содержать хотя бы одну пару лампочек одного цвета, находящуюся рядом друг с другом. Обратите внимание, что сотрудники должны использовать все лампочки, которые вы предоставите.</p><p>Так что Поликарп купил несколько наборов лампочек, и теперь интересуется, смогут ли сотрудники собрать гирлянду из каждого из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов лампочек, которые купил Поликарп.</p><p>В каждой из следующих $$$t$$$ строк записаны по три целых числа $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^9$$$) — количество красных, зеленых и синих лампочек, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк — для каждого набора лампочек выведите «<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> 3 3 3 3 1 10 2 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No Yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первые два набора описаны в условии.</p><p>В третьем наборе можно собрать гирлянду «<span class="tex-font-style-tt">RBRG</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:53: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:'812491f30eda9d40',t:'MTY5NjY2NTIwMy44NzEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1279B
1279
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$$$ частей. Вася тратит $$$a_i$$$ секунд на $$$i$$$-ю часть. При этом он не может менять порядок частей в стишке: сначала он рассказывает часть, которая занимает $$$a_1$$$ секунд, затем — часть, которая занимает $$$a_2$$$ секунд и так далее. После того, как Вася закончил зачитывать стишок, Вася получает по подарку за каждую полностью рассказаную часть.</p><p>Вася может пропустить не более одной части стишка (если он пропустит больше, Санта обязательно это заметит).</p><p>Санта будет слушать Васин стишок не более $$$s$$$ секунд. Например, если $$$s = 10$$$, $$$a = [100, 9, 1, 1]$$$, и Вася пропускает первую часть стишка, то он получает два подарка.</p><p>Обратить внимание, что Вася может зачитать стишок полностью (если ему хватит времени). </p><p>Определите часть, которую нужно пропустить Васе, для того чтобы получить максимальное количество подарков. Если Васе нужно зачитать стих полностью, выведите <span class="tex-font-style-tt">0</span>. Если существует несколько правильных ответов — выведите любой из них.</p><p>Вам нужно ответить на $$$t$$$ наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два числа $$$n$$$ и $$$s$$$ ($$$1 \le n \le 10^5, 1 \le s \le 10^9$$$) — количество частей в стишке и количество секунд, которое Санта будет слушать Васю соответственно.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите одно число — номер части, которую нужно пропустить Васе, для того чтобы получить максимальное количество подарков. Если Васе нужно зачитать стих полностью, выведите <span class="tex-font-style-tt">0</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 7 11 2 9 1 3 18 1 4 4 35 11 9 10 7 1 8 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Вася получит три подарка, если пропустит вторую часть стиха.</p><p>Во втором наборе входных данных не важно какую часть стиха пропустить.</p><p>В третьем наборе входных данных Вася может прочитать стих полностью.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="91fe6b3d65a9d0c6b0015372e13d7a7c"/> <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="3fd08d06ea3f0cde970e15e21c8ce523e24f62d3"/> <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='91fe6b3d65a9d0c6b0015372e13d7a7c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1279%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='91fe6b3d65a9d0c6b0015372e13d7a7c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1279">Educational Codeforces Round 79 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='91fe6b3d65a9d0c6b0015372e13d7a7c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1279/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='91fe6b3d65a9d0c6b0015372e13d7a7c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="504274"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='91fe6b3d65a9d0c6b0015372e13d7a7c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="504274"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72494" title="Educational Codeforces Round 79 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10179:10180" 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/72577" title="Разбор Educational Codeforces Round 79" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10201:10202" 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/1279">Задачи</a></li> <li><a href="/contest/1279/submit">Отослать</a></li> <li><a href="/contest/1279/my">Мои посылки</a></li> <li><a href="/contest/1279/status">Статус</a></li> <li><a href="/contest/1279/hacks">Взломы</a></li> <li><a href="/contest/1279/standings">Положение</a></li> <li><a href="/contest/1279/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8d6a76a13c3474efa7c8c1f9cb1f57d4b17d7a4d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ частей. Вася тратит $$$a_i$$$ секунд на $$$i$$$-ю часть. При этом он не может менять порядок частей в стишке: сначала он рассказывает часть, которая занимает $$$a_1$$$ секунд, затем — часть, которая занимает $$$a_2$$$ секунд и так далее. После того, как Вася закончил зачитывать стишок, Вася получает по подарку за каждую полностью рассказаную часть.</p><p>Вася может пропустить не более одной части стишка (если он пропустит больше, Санта обязательно это заметит).</p><p>Санта будет слушать Васин стишок не более $$$s$$$ секунд. Например, если $$$s = 10$$$, $$$a = [100, 9, 1, 1]$$$, и Вася пропускает первую часть стишка, то он получает два подарка.</p><p>Обратить внимание, что Вася может зачитать стишок полностью (если ему хватит времени). </p><p>Определите часть, которую нужно пропустить Васе, для того чтобы получить максимальное количество подарков. Если Васе нужно зачитать стих полностью, выведите <span class="tex-font-style-tt">0</span>. Если существует несколько правильных ответов — выведите любой из них.</p><p>Вам нужно ответить на $$$t$$$ наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два числа $$$n$$$ и $$$s$$$ ($$$1 \le n \le 10^5, 1 \le s \le 10^9$$$) — количество частей в стишке и количество секунд, которое Санта будет слушать Васю соответственно.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите одно число — номер части, которую нужно пропустить Васе, для того чтобы получить максимальное количество подарков. Если Васе нужно зачитать стих полностью, выведите <span class="tex-font-style-tt">0</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 7 11 2 9 1 3 18 1 4 4 35 11 9 10 7 1 8 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Вася получит три подарка, если пропустит вторую часть стиха.</p><p>Во втором наборе входных данных не важно какую часть стиха пропустить.</p><p>В третьем наборе входных данных Вася может прочитать стих полностью.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=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:53:25</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'812491fbdcb00065',t:'MTY5NjY2NTIwNS4xODUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1300"]
1279C
1279
C
ru
C. Стопка подарков
<div class="problem-statement"><div class="header"><div class="title">C. Стопка подарков</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дед Мороз должен отправить подарки детям. У него есть большая стопка, в которой $$$n$$$ подарков, пронумерованных от $$$1$$$ до $$$n$$$; у самого верхнего подарка номер $$$a_1$$$, у подарка под ним номер $$$a_2$$$, и так далее; у самого нижнего подарка номер $$$a_n$$$. Все номера различны.</p><p>У Деда Мороза есть список из $$$m$$$ <span class="tex-font-style-bf">различных</span> номеров подарков, которые он должен отправить: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. Он отправит их <span class="tex-font-style-bf">в том порядке, в котором они располагаются в списке</span>.</p><p>Чтобы отправить подарок, Дед Мороз должен найти его в стопке, убрав все подарки, которые выше нужного; затем он берет нужный ему подарок и возвращает убранные подарки обратно на вершину стопки. Если над подарком, который нужен Деду Морозу, $$$k$$$ других подарков, на эти действия тратится $$$2k + 1$$$ секунд. К счастью, Дед Мороз может ускорить процесс — когда он возвращает подарки в стопку, он может делать это в любом порядке (только те подарки, которые были над нужным подарком, могут поменять свой порядок; остальные подарки остаются на своих местах в стопке). Когда Дед Мороз отправляет подарок, он исчезает из стопки.</p><p>Какое минимальное время потребуется Деду Морозу, чтобы отправить подарки, если он будет каждый раз располагать возвращаемые подарки оптимальным образом? Дед Мороз не может как-то взаимодействовать со стопкой другими способами.</p><p>Ваша программа должна уметь обрабатывать $$$t$$$ наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Затем идут сами наборы входных данных, каждый из которых состоит из трех строк.</p><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) — количество подарков в стопке и количество подарков, которые нужно отправить.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, все $$$a_i$$$ различны) — порядок подарков в стопке.</p><p>В третьей строке заданы $$$m$$$ целых чисел $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, все $$$b_i$$$ различны) — упорядоченный список подарков, которые нужно отправить.</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 3 3 1 2 3 2 1 7 2 2 1 7 3 4 5 6 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 8 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="014fff2bee1e945360a46df0cfb26762"/> <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="3fd08d06ea3f0cde970e15e21c8ce523e24f62d3"/> <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='014fff2bee1e945360a46df0cfb26762'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1279%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='014fff2bee1e945360a46df0cfb26762'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1279">Educational Codeforces Round 79 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='014fff2bee1e945360a46df0cfb26762'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1279/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='014fff2bee1e945360a46df0cfb26762'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="504275"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='014fff2bee1e945360a46df0cfb26762'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="504275"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72494" title="Educational Codeforces Round 79 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10179:10180" 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/72577" title="Разбор Educational Codeforces Round 79" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10201:10202" 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/1279">Задачи</a></li> <li><a href="/contest/1279/submit">Отослать</a></li> <li><a href="/contest/1279/my">Мои посылки</a></li> <li><a href="/contest/1279/status">Статус</a></li> <li><a href="/contest/1279/hacks">Взломы</a></li> <li><a href="/contest/1279/standings">Положение</a></li> <li><a href="/contest/1279/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_96ed4c2069f8604958e1b1da2a47852594c27620"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Стопка подарков</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дед Мороз должен отправить подарки детям. У него есть большая стопка, в которой $$$n$$$ подарков, пронумерованных от $$$1$$$ до $$$n$$$; у самого верхнего подарка номер $$$a_1$$$, у подарка под ним номер $$$a_2$$$, и так далее; у самого нижнего подарка номер $$$a_n$$$. Все номера различны.</p><p>У Деда Мороза есть список из $$$m$$$ <span class="tex-font-style-bf">различных</span> номеров подарков, которые он должен отправить: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. Он отправит их <span class="tex-font-style-bf">в том порядке, в котором они располагаются в списке</span>.</p><p>Чтобы отправить подарок, Дед Мороз должен найти его в стопке, убрав все подарки, которые выше нужного; затем он берет нужный ему подарок и возвращает убранные подарки обратно на вершину стопки. Если над подарком, который нужен Деду Морозу, $$$k$$$ других подарков, на эти действия тратится $$$2k + 1$$$ секунд. К счастью, Дед Мороз может ускорить процесс — когда он возвращает подарки в стопку, он может делать это в любом порядке (только те подарки, которые были над нужным подарком, могут поменять свой порядок; остальные подарки остаются на своих местах в стопке). Когда Дед Мороз отправляет подарок, он исчезает из стопки.</p><p>Какое минимальное время потребуется Деду Морозу, чтобы отправить подарки, если он будет каждый раз располагать возвращаемые подарки оптимальным образом? Дед Мороз не может как-то взаимодействовать со стопкой другими способами.</p><p>Ваша программа должна уметь обрабатывать $$$t$$$ наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Затем идут сами наборы входных данных, каждый из которых состоит из трех строк.</p><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) — количество подарков в стопке и количество подарков, которые нужно отправить.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, все $$$a_i$$$ различны) — порядок подарков в стопке.</p><p>В третьей строке заданы $$$m$$$ целых чисел $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, все $$$b_i$$$ различны) — упорядоченный список подарков, которые нужно отправить.</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 3 3 1 2 3 2 1 7 2 2 1 7 3 4 5 6 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 8 </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:53: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:'8124920418f49d63',t:'MTY5NjY2NTIwNi40OTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1400"]
1279D
1279
D
ru
D. Робот Деда Мороза
<div class="problem-statement"><div class="header"><div class="title">D. Робот Деда Мороза</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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$$$-й малыш попросил подарить ему один из $$$k_i$$$ различных предметов в качестве подарка. Некоторые предметы могли попросить несколько детей.</p><p>Дед Мороз очень занят, поэтому он хочет, чтобы Новогодний Робот выбрал подарки для всех детей. К сожалению, алгоритм выбора подарков Роботом содержит ошибку. Чтобы выбрать подарок для какого-то малыша, Робот делает следующее:</p><ul> <li> равновероятно выбирает одного ребенка $$$x$$$ среди всех $$$n$$$ детей; </li><li> равновероятно выбирает некоторый предмет $$$y$$$ среди всех $$$k_x$$$ предметов, которые хочет ребенок $$$x$$$; </li><li> равновероятно выбирает ребенка $$$z$$$, который получит подарок, среди всех $$$n$$$ детей (этот выбор не зависит от выбора $$$x$$$ и $$$y$$$); результирующая тройка $$$(x, y, z)$$$ называется <span class="tex-font-style-bf">выбором</span> Робота. </li></ul><p>Если ребенок $$$z$$$ хотел получить предмет $$$y$$$, то выбор <span class="tex-font-style-bf">корректный</span>. В противном случае, выбор Робота будет <span class="tex-font-style-bf">некорректным</span>.</p><p>Дед Мороз знает об ошибке, но он не может оценить, действительно ли эта ошибка серьезна. Для этого он хочет знать вероятность того, что один выбор, сгенерированный в соответствии с вышеупомянутым алгоритмом, корректен. Вы можете ему помочь?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^6$$$) — количество детей, которые написали свои письма Деду Морозу.</p><p>Далее следуют $$$n$$$ строк, $$$i$$$-я из них содержит список предметов, которые хочет $$$i$$$-й ребенок, в следующем формате: $$$k_i$$$ $$$a_{i, 1}$$$ $$$a_{i, 2}$$$ ... $$$a_{i, k_i}$$$ ($$$1 \le k_i, a_{i, j} \le 10^6$$$), где $$$k_i$$$ — это количество предметов, которые хочет $$$i$$$-й ребенок, а $$$a_{i, j}$$$ — это сами предметы. Ни один предмет не содержится в одном и том же списке более одного раза.</p><p>Гарантируется, что $$$\sum \limits_{i = 1}^{n} k_i \le 10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите вероятность того, что Робот сделает <span class="tex-font-style-bf">корректный</span> выбор следующим образом:</p><p>Пусть эта вероятность представлена в виде неприводимой дроби $$$\frac{x}{y}$$$. Вам необходимо вывести $$$x \cdot y^{-1} \mod 998244353$$$, где $$$y^{-1}$$$ является обратным элементом к $$$y$$$ по модулю $$$998244353$$$ (такое целое число, что $$$y \cdot y^{-1}$$$ имеет остаток $$$1$$$ по модулю $$$998244353$$$).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 124780545 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 1 2 2 3 1 3 2 4 3 2 1 4 3 4 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 798595483 </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="29ab040cef34fee8dee449d3f815fddc"/> <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="3fd08d06ea3f0cde970e15e21c8ce523e24f62d3"/> <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='29ab040cef34fee8dee449d3f815fddc'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1279%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='29ab040cef34fee8dee449d3f815fddc'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1279">Educational Codeforces Round 79 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='29ab040cef34fee8dee449d3f815fddc'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1279/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др."> теория вероятностей </span> </div> <div class="roundbox borderTopRound 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='29ab040cef34fee8dee449d3f815fddc'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="504276"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='29ab040cef34fee8dee449d3f815fddc'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="504276"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72494" title="Educational Codeforces Round 79 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10179:10180" 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/72577" title="Разбор Educational Codeforces Round 79" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10201:10202" 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/1279">Задачи</a></li> <li><a href="/contest/1279/submit">Отослать</a></li> <li><a href="/contest/1279/my">Мои посылки</a></li> <li><a href="/contest/1279/status">Статус</a></li> <li><a href="/contest/1279/hacks">Взломы</a></li> <li><a href="/contest/1279/standings">Положение</a></li> <li><a href="/contest/1279/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0335d92cfb8d6173844cfa98b793134eced2032b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Робот Деда Мороза</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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$$$-й малыш попросил подарить ему один из $$$k_i$$$ различных предметов в качестве подарка. Некоторые предметы могли попросить несколько детей.</p><p>Дед Мороз очень занят, поэтому он хочет, чтобы Новогодний Робот выбрал подарки для всех детей. К сожалению, алгоритм выбора подарков Роботом содержит ошибку. Чтобы выбрать подарок для какого-то малыша, Робот делает следующее:</p><ul> <li> равновероятно выбирает одного ребенка $$$x$$$ среди всех $$$n$$$ детей; </li><li> равновероятно выбирает некоторый предмет $$$y$$$ среди всех $$$k_x$$$ предметов, которые хочет ребенок $$$x$$$; </li><li> равновероятно выбирает ребенка $$$z$$$, который получит подарок, среди всех $$$n$$$ детей (этот выбор не зависит от выбора $$$x$$$ и $$$y$$$); результирующая тройка $$$(x, y, z)$$$ называется <span class="tex-font-style-bf">выбором</span> Робота. </li></ul><p>Если ребенок $$$z$$$ хотел получить предмет $$$y$$$, то выбор <span class="tex-font-style-bf">корректный</span>. В противном случае, выбор Робота будет <span class="tex-font-style-bf">некорректным</span>.</p><p>Дед Мороз знает об ошибке, но он не может оценить, действительно ли эта ошибка серьезна. Для этого он хочет знать вероятность того, что один выбор, сгенерированный в соответствии с вышеупомянутым алгоритмом, корректен. Вы можете ему помочь?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^6$$$) — количество детей, которые написали свои письма Деду Морозу.</p><p>Далее следуют $$$n$$$ строк, $$$i$$$-я из них содержит список предметов, которые хочет $$$i$$$-й ребенок, в следующем формате: $$$k_i$$$ $$$a_{i, 1}$$$ $$$a_{i, 2}$$$ ... $$$a_{i, k_i}$$$ ($$$1 \le k_i, a_{i, j} \le 10^6$$$), где $$$k_i$$$ — это количество предметов, которые хочет $$$i$$$-й ребенок, а $$$a_{i, j}$$$ — это сами предметы. Ни один предмет не содержится в одном и том же списке более одного раза.</p><p>Гарантируется, что $$$\sum \limits_{i = 1}^{n} k_i \le 10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите вероятность того, что Робот сделает <span class="tex-font-style-bf">корректный</span> выбор следующим образом:</p><p>Пусть эта вероятность представлена в виде неприводимой дроби $$$\frac{x}{y}$$$. Вам необходимо вывести $$$x \cdot y^{-1} \mod 998244353$$$, где $$$y^{-1}$$$ является обратным элементом к $$$y$$$ по модулю $$$998244353$$$ (такое целое число, что $$$y \cdot y^{-1}$$$ имеет остаток $$$1$$$ по модулю $$$998244353$$$).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 124780545 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 1 2 2 3 1 3 2 4 3 2 1 4 3 4 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 798595483 </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:53:27</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'8124920c4fff2de5',t:'MTY5NjY2NTIwNy44MTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\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"]
["\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*1700"]
1279E
1279
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><span class="tex-font-style-it">Да, мы не смогли придумать новогоднюю легенду для этой задачи</span>.</p><p>Перестановка длины $$$n$$$ — это массив $$$n$$$ целых чисел, таких что каждое целое число от $$$1$$$ до $$$n$$$ появляется в нем ровно один раз.</p><p>Элемент $$$y$$$ перестановки $$$p$$$ достижим из элемента $$$x$$$, Если $$$x = y$$$, или $$$p_x = y$$$, или $$$p_{p_x} = y$$$ и так далее.</p><p>Определим <span class="tex-font-style-bf">декомпозицию</span> перестановки $$$p$$$ следующим образом: сначала у нас есть перестановка $$$p$$$, все элементы которой <span class="tex-font-style-bf">не помечены</span>, и пустой список $$$l$$$. Затем мы делаем следующее: пока хотя бы один элемент <span class="tex-font-style-bf">не помечен</span> в $$$p$$$, находим самый левый такой элемент, перечисляем все элементы, которые достижимы из него <span class="tex-font-style-bf">в порядке их появления в $$$p$$$</span>, помечаем все эти элементы, затем циклически сдвигаем список этих элементов так, чтобы максимум появился в первой позиции, и добавляем этот список <span class="tex-font-style-bf">как элемент</span> в $$$l$$$. После того, как все элементы помечены, $$$l$$$ является результатом этой декомпозиции.</p><p>Например, если мы хотим построить декомпозицию $$$p = [5, 4, 2, 3, 1, 7, 8, 6]$$$, мы делаем следующее:</p><ol> <li> изначально $$$p = [5, 4, 2, 3, 1, 7, 8, 6]$$$ (жирным шрифтом выделены помеченные элементы), $$$l = []$$$; </li><li> самый левый не помеченный элемент — $$$5$$$; $$$5$$$ и $$$1$$$ достижимы из него, поэтому список, который мы хотим сдвинуть, — $$$[5, 1]$$$; нет необходимости сдвигать его, так как максимум уже является первым элементом; </li><li> $$$p = [\textbf{5}, 4, 2, 3, \textbf{1}, 7, 8, 6]$$$, $$$l = [[5, 1]]$$$; </li><li> самый левый не помеченный элемент — $$$4$$$, список достижимых элементов из него — это $$$[4, 2, 3]$$$; максимум уже первый элемент, поэтому сдвигать его не нужно; </li><li> $$$p = [\textbf{5}, \textbf{4}, \textbf{2}, \textbf{3}, \textbf{1}, 7, 8, 6]$$$, $$$l = [[5, 1], [4, 2, 3]]$$$; </li><li> самый левый не помеченный элемент — $$$7$$$, список достижимых элементов из него — это $$$[7, 8, 6]$$$; мы должны сдвинуть его, чтобы он стал $$$[8, 6, 7]$$$; </li><li> $$$p = [\textbf{5}, \textbf{4}, \textbf{2}, \textbf{3}, \textbf{1}, \textbf{7}, \textbf{8}, \textbf{6}]$$$, $$$l = [[5, 1], [4, 2, 3], [8, 6, 7]]$$$; </li><li> все элементы помечены, так что $$$[[5, 1], [4, 2, 3], [8, 6, 7]]$$$ — результат декомпозиции. </li></ol><p>Определим <span class="tex-font-style-it">новогоднее преобразование</span> перестановки следующим образом: построим декомпозицию этой перестановки; затем отсортируем все списки в декомпозиции по возрастанию первых элементов (мы не меняем местами элементы в этих списках, только сами списки); затем объединим списки в один список, который становится новой перестановкой. Например, <span class="tex-font-style-it">новогоднее преобразование</span> $$$p = [5, 4, 2, 3, 1, 7, 8, 6]$$$ строится следующим образом:</p><ol> <li> декомпозиция равна $$$[[5, 1], [4, 2, 3], [8, 6, 7]]$$$; </li><li> после сортировки, декомпозиция становится равна $$$[[4, 2, 3], [5, 1], [8, 6, 7]]$$$; </li><li> $$$[4, 2, 3, 5, 1, 8, 6, 7]$$$ — результат преобразования. </li></ol><p>Назовем перестановку <span class="tex-font-style-bf">хорошей</span>, если результат ее преобразования совпадает с самой перестановкой. Например, $$$[4, 3, 1, 2, 8, 5, 6, 7]$$$ это хорошая перестановка; а $$$[5, 4, 2, 3, 1, 7, 8, 6]$$$ плохая, так как результатом преобразования является $$$[4, 2, 3, 5, 1, 8, 6, 7]$$$.</p><p>Ваша задача состоит в следующем: при заданных $$$n$$$ и $$$k$$$ найти $$$k$$$-ю (лексикографически) хорошую перестановку длины $$$n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 10^{18}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите ответ на него следующим образом: если число хороших перестановок длины $$$n$$$ меньше $$$k$$$, выведите одно целое число $$$-1$$$; в противном случае выведите $$$k$$$-ю (в лексикографическом порядке) хорошую перестановку из $$$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 3 5 15 4 13 6 8 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="26ad1c3cca77742f690f6e8e471e3969"/> <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="3fd08d06ea3f0cde970e15e21c8ce523e24f62d3"/> <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='26ad1c3cca77742f690f6e8e471e3969'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1279%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='26ad1c3cca77742f690f6e8e471e3969'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1279">Educational Codeforces Round 79 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='26ad1c3cca77742f690f6e8e471e3969'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1279/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound 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='26ad1c3cca77742f690f6e8e471e3969'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="504277"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='26ad1c3cca77742f690f6e8e471e3969'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="504277"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72494" title="Educational Codeforces Round 79 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10179:10180" 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/72577" title="Разбор Educational Codeforces Round 79" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10201:10202" 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/1279">Задачи</a></li> <li><a href="/contest/1279/submit">Отослать</a></li> <li><a href="/contest/1279/my">Мои посылки</a></li> <li><a href="/contest/1279/status">Статус</a></li> <li><a href="/contest/1279/hacks">Взломы</a></li> <li><a href="/contest/1279/standings">Положение</a></li> <li><a href="/contest/1279/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_17b6ff4a64846a2aa165ad8742211f17b1148598"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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><span class="tex-font-style-it">Да, мы не смогли придумать новогоднюю легенду для этой задачи</span>.</p><p>Перестановка длины $$$n$$$ — это массив $$$n$$$ целых чисел, таких что каждое целое число от $$$1$$$ до $$$n$$$ появляется в нем ровно один раз.</p><p>Элемент $$$y$$$ перестановки $$$p$$$ достижим из элемента $$$x$$$, Если $$$x = y$$$, или $$$p_x = y$$$, или $$$p_{p_x} = y$$$ и так далее.</p><p>Определим <span class="tex-font-style-bf">декомпозицию</span> перестановки $$$p$$$ следующим образом: сначала у нас есть перестановка $$$p$$$, все элементы которой <span class="tex-font-style-bf">не помечены</span>, и пустой список $$$l$$$. Затем мы делаем следующее: пока хотя бы один элемент <span class="tex-font-style-bf">не помечен</span> в $$$p$$$, находим самый левый такой элемент, перечисляем все элементы, которые достижимы из него <span class="tex-font-style-bf">в порядке их появления в $$$p$$$</span>, помечаем все эти элементы, затем циклически сдвигаем список этих элементов так, чтобы максимум появился в первой позиции, и добавляем этот список <span class="tex-font-style-bf">как элемент</span> в $$$l$$$. После того, как все элементы помечены, $$$l$$$ является результатом этой декомпозиции.</p><p>Например, если мы хотим построить декомпозицию $$$p = [5, 4, 2, 3, 1, 7, 8, 6]$$$, мы делаем следующее:</p><ol> <li> изначально $$$p = [5, 4, 2, 3, 1, 7, 8, 6]$$$ (жирным шрифтом выделены помеченные элементы), $$$l = []$$$; </li><li> самый левый не помеченный элемент — $$$5$$$; $$$5$$$ и $$$1$$$ достижимы из него, поэтому список, который мы хотим сдвинуть, — $$$[5, 1]$$$; нет необходимости сдвигать его, так как максимум уже является первым элементом; </li><li> $$$p = [\textbf{5}, 4, 2, 3, \textbf{1}, 7, 8, 6]$$$, $$$l = [[5, 1]]$$$; </li><li> самый левый не помеченный элемент — $$$4$$$, список достижимых элементов из него — это $$$[4, 2, 3]$$$; максимум уже первый элемент, поэтому сдвигать его не нужно; </li><li> $$$p = [\textbf{5}, \textbf{4}, \textbf{2}, \textbf{3}, \textbf{1}, 7, 8, 6]$$$, $$$l = [[5, 1], [4, 2, 3]]$$$; </li><li> самый левый не помеченный элемент — $$$7$$$, список достижимых элементов из него — это $$$[7, 8, 6]$$$; мы должны сдвинуть его, чтобы он стал $$$[8, 6, 7]$$$; </li><li> $$$p = [\textbf{5}, \textbf{4}, \textbf{2}, \textbf{3}, \textbf{1}, \textbf{7}, \textbf{8}, \textbf{6}]$$$, $$$l = [[5, 1], [4, 2, 3], [8, 6, 7]]$$$; </li><li> все элементы помечены, так что $$$[[5, 1], [4, 2, 3], [8, 6, 7]]$$$ — результат декомпозиции. </li></ol><p>Определим <span class="tex-font-style-it">новогоднее преобразование</span> перестановки следующим образом: построим декомпозицию этой перестановки; затем отсортируем все списки в декомпозиции по возрастанию первых элементов (мы не меняем местами элементы в этих списках, только сами списки); затем объединим списки в один список, который становится новой перестановкой. Например, <span class="tex-font-style-it">новогоднее преобразование</span> $$$p = [5, 4, 2, 3, 1, 7, 8, 6]$$$ строится следующим образом:</p><ol> <li> декомпозиция равна $$$[[5, 1], [4, 2, 3], [8, 6, 7]]$$$; </li><li> после сортировки, декомпозиция становится равна $$$[[4, 2, 3], [5, 1], [8, 6, 7]]$$$; </li><li> $$$[4, 2, 3, 5, 1, 8, 6, 7]$$$ — результат преобразования. </li></ol><p>Назовем перестановку <span class="tex-font-style-bf">хорошей</span>, если результат ее преобразования совпадает с самой перестановкой. Например, $$$[4, 3, 1, 2, 8, 5, 6, 7]$$$ это хорошая перестановка; а $$$[5, 4, 2, 3, 1, 7, 8, 6]$$$ плохая, так как результатом преобразования является $$$[4, 2, 3, 5, 1, 8, 6, 7]$$$.</p><p>Ваша задача состоит в следующем: при заданных $$$n$$$ и $$$k$$$ найти $$$k$$$-ю (лексикографически) хорошую перестановку длины $$$n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 10^{18}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите ответ на него следующим образом: если число хороших перестановок длины $$$n$$$ меньше $$$k$$$, выведите одно целое число $$$-1$$$; в противном случае выведите $$$k$$$-ю (в лексикографическом порядке) хорошую перестановку из $$$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 3 5 15 4 13 6 8 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:53: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:'812492148a5616f4',t:'MTY5NjY2NTIwOS4xNDQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2700"]
1279F
1279
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>Наступает новый год. Это значит, что на codeforces пришла пора менять хендлы. Мишке захотелось поменять свой хендл, но таким образом, чтобы люди не забыли, кто он такой.</p><p>Чтобы все получилось так, как он хочет, он решил менять только регистры букв. Более формально, за <span class="tex-font-style-bf">одну</span> смену хендла он может выбрать любой отрезок своего хендла $$$[i; i + l - 1]$$$ и сделать <span class="tex-font-style-tt">tolower</span> или <span class="tex-font-style-tt">toupper</span> ко всем буквам своего хендла на этом отрезке (более формально, поменять все строчные буквы на отрезке на соответствующие прописные или наоборот). Длина $$$l$$$ фиксирована для всех смен.</p><p>Так как на codeforces нельзя слишком часто менять хендлы, всего Мишка может сделать не более $$$k$$$ таких операций. Какого <span class="tex-font-style-bf">минимального</span> значения может быть $$$min(lower, upper)$$$ (где $$$lower$$$ — количество строчных букв, а $$$upper$$$ — количество прописных букв) после оптимальной последовательности смен?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит три целых числа $$$n, k$$$ и $$$l$$$ ($$$1 \le n, k, l \le 10^6, l \le n)$$$ — длину хендла Мишки, количество смен и длину отрезка.</p><p>Вторая строка входных данных содержит одну строку $$$s$$$, состоящую из $$$n$$$ строчных и прописных букв латинского алфавита — хендл Мишки.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное значение, которого может достигнуть $$$min(lower, upper)$$$ после того, как Мишка сменит свой хендл не более $$$k$$$ раз так, как описано в условии задачи.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 1 4 PikMike </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 15 2 2 AaAaAAaaAAAAaaA </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 14 2 6 aBcdEFGHIJklMn </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 9 2 2 aAaAAAaaA </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="a5db7affd4d7413b348faf2f58e11e87"/> <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="3fd08d06ea3f0cde970e15e21c8ce523e24f62d3"/> <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='a5db7affd4d7413b348faf2f58e11e87'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1279%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='a5db7affd4d7413b348faf2f58e11e87'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1279">Educational Codeforces Round 79 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a5db7affd4d7413b348faf2f58e11e87'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1279/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a5db7affd4d7413b348faf2f58e11e87'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="504278"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a5db7affd4d7413b348faf2f58e11e87'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="504278"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72494" title="Educational Codeforces Round 79 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10179:10180" 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/72577" title="Разбор Educational Codeforces Round 79" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10201:10202" 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/1279">Задачи</a></li> <li><a href="/contest/1279/submit">Отослать</a></li> <li><a href="/contest/1279/my">Мои посылки</a></li> <li><a href="/contest/1279/status">Статус</a></li> <li><a href="/contest/1279/hacks">Взломы</a></li> <li><a href="/contest/1279/standings">Положение</a></li> <li><a href="/contest/1279/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_bcc03216b6975a258b5587055add275709110fb6"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Наступает новый год. Это значит, что на codeforces пришла пора менять хендлы. Мишке захотелось поменять свой хендл, но таким образом, чтобы люди не забыли, кто он такой.</p><p>Чтобы все получилось так, как он хочет, он решил менять только регистры букв. Более формально, за <span class="tex-font-style-bf">одну</span> смену хендла он может выбрать любой отрезок своего хендла $$$[i; i + l - 1]$$$ и сделать <span class="tex-font-style-tt">tolower</span> или <span class="tex-font-style-tt">toupper</span> ко всем буквам своего хендла на этом отрезке (более формально, поменять все строчные буквы на отрезке на соответствующие прописные или наоборот). Длина $$$l$$$ фиксирована для всех смен.</p><p>Так как на codeforces нельзя слишком часто менять хендлы, всего Мишка может сделать не более $$$k$$$ таких операций. Какого <span class="tex-font-style-bf">минимального</span> значения может быть $$$min(lower, upper)$$$ (где $$$lower$$$ — количество строчных букв, а $$$upper$$$ — количество прописных букв) после оптимальной последовательности смен?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит три целых числа $$$n, k$$$ и $$$l$$$ ($$$1 \le n, k, l \le 10^6, l \le n)$$$ — длину хендла Мишки, количество смен и длину отрезка.</p><p>Вторая строка входных данных содержит одну строку $$$s$$$, состоящую из $$$n$$$ строчных и прописных букв латинского алфавита — хендл Мишки.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное значение, которого может достигнуть $$$min(lower, upper)$$$ после того, как Мишка сменит свой хендл не более $$$k$$$ раз так, как описано в условии задачи.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 1 4 PikMike </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 15 2 2 AaAaAAaaAAAAaaA </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 14 2 6 aBcdEFGHIJklMn </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 9 2 2 aAaAAAaaA </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:53: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:'8124921ccfde005f',t:'MTY5NjY2NTIxMC40NDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2800"]
1280A
1280
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>Мы начинаем со строки $$$s$$$, состоящей только из цифр $$$1$$$, $$$2$$$ или $$$3$$$. Будем обозначать длину строки $$$s$$$ как $$$|s|$$$. Для всех $$$i$$$ от $$$1$$$ до $$$|s|$$$ $$$i$$$-й символ строки $$$s$$$ обозначим как $$$s_i$$$.</p><p>Где-то в строке стоит курсор. Позиция курсора $$$\ell$$$ обозначается целым числом из множества $$$\{0, \ldots, |s|\}$$$, и имеет следующее значение: </p><ul> <li> если $$$\ell = 0$$$, тогда курсор расположен перед первым символом строки $$$s$$$. </li><li> если $$$\ell = |s|$$$, тогда курсор расположен после последнего символа строки $$$s$$$. </li><li> если $$$0 &lt; \ell &lt; |s|$$$, тогда курсор расположен между символами $$$s_\ell$$$ и $$$s_{\ell+1}$$$. </li></ul><p>Обозначим за $$$s_\text{left}$$$ строку, находящуюся левее курсора и за $$$s_\text{right}$$$ строку находящуюся правее курсора.</p><p>Также есть строка $$$c$$$, которая называется <span class="tex-font-style-underline">буфером</span>, которая изначально пуста. Всего существует три типа действий:</p><ul> <li> <span class="tex-font-style-bf">Передвижение</span>. Передвинуть курсор на один символ вправо. Это увеличивает $$$\ell$$$ на единицу. </li><li> <span class="tex-font-style-bf">Вырезание</span>. Присвоить $$$c \leftarrow s_\text{right}$$$, затем присвоить $$$s \leftarrow s_\text{left}$$$. </li><li> <span class="tex-font-style-bf">Вставка</span>. Добавить значение $$$c$$$ в конец строки $$$s$$$. Заметьте, что это никак не меняет $$$c$$$. </li></ul><p>Изначально курсор находится в позиции $$$\ell = 0$$$. Затем, исполняется следующая процедура:</p><ol> <li> Применить передвижение один раз. </li><li> Применить вырезание один раз. </li><li> Несколько применить вставку, количество раз равно $$$s_\ell$$$. </li><li> Если $$$\ell = x$$$, остановиться. Иначе, вернуться к шагу 1. </li></ol><p>Вам дана изначальная строка $$$s$$$ и целое число $$$x$$$. Какой будет длина строки $$$s$$$ когда процедура остановится? Так как это число может быть очень большим, выведите его остаток при делении на $$$10^9 + 7$$$. </p><p>Гарантируется, что $$$\ell \le |s|$$$ в любой момент времени.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 1000$$$), количество наборов входных данных. В следующих строках находятся их описания.</p><p>В первой строке каждого набора входных данных записано единственное целое число $$$x$$$ ($$$1 \le x \le 10^6$$$). Во второй строке находится изначальная строка $$$s$$$ ($$$1 \le |s| \le 500$$$). Гарантируется, что $$$s$$$ состоит только из символов «<span class="tex-font-style-tt">1</span>», «<span class="tex-font-style-tt">2</span>», «<span class="tex-font-style-tt">3</span>».</p><p>Гарантируется, что сумма $$$x$$$ по всем тестовым случаям не превосходит $$$10^6$$$. Гарантируется, что во всех тестовых случаях во время процедуры $$$\ell \le |s|$$$ в любой момент времени.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите остаток при делении длины строки после процедуры на $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 231 7 2323 6 333 24 133321333 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 25 1438 1101 686531475 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Давайте проиллюстрируем, что происходит в первом тестовом случае. Изначально у нас $$$s = $$$ <span class="tex-font-style-tt">231</span>. Изначально, $$$\ell = 0$$$ и $$$c = \varepsilon$$$ (пустая строка). Вот как изменяются эти значения в ходе процедуры:</p><ul><p> </p><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 1$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2</span> и $$$c = $$$ <span class="tex-font-style-tt">31</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">2</span> раза:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 1 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 2$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23</span> и $$$c = $$$ <span class="tex-font-style-tt">131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">3</span> раза:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 2 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим$$$\ell = 3$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">231</span> и $$$c = $$$ <span class="tex-font-style-tt">31131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">1</span> раз:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 3 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 4$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2313</span> и $$$c = $$$ <span class="tex-font-style-tt">1131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">3</span> раза:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2313113113111311311131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 4 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 5$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131</span> и $$$c = $$$ <span class="tex-font-style-tt">13113111311311131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">1</span> раз:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2313113113111311311131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 5 = x$$$, поэтому мы останавливаемся. </li></ul><p>В конце процедуры, $$$s$$$ имеет длину $$$25$$$. </p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="3585f3a49ca734a7b61ad0673a36eafa"/> <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="e32544b9cb685be4a903dab3307027ab419a190c"/> <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='3585f3a49ca734a7b61ad0673a36eafa'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1280%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='3585f3a49ca734a7b61ad0673a36eafa'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1280">Codeforces Round 607 (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='3585f3a49ca734a7b61ad0673a36eafa'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1280/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='3585f3a49ca734a7b61ad0673a36eafa'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="495760"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3585f3a49ca734a7b61ad0673a36eafa'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="495760"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72165" title="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10064" resourceName="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" resourceManual="true" src="//codeforces.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/72212" title="Codeforces Round #607 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10080" resourceName="Codeforces Round #607 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/1280">Задачи</a></li> <li><a href="/contest/1280/submit">Отослать</a></li> <li><a href="/contest/1280/my">Мои посылки</a></li> <li><a href="/contest/1280/status">Статус</a></li> <li><a href="/contest/1280/hacks">Взломы</a></li> <li><a href="/contest/1280/room/1">Комната</a></li> <li><a href="/contest/1280/standings">Положение</a></li> <li><a href="/contest/1280/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b4a535148186c5ab507ed7ce529374535be30ad4"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Мы начинаем со строки $$$s$$$, состоящей только из цифр $$$1$$$, $$$2$$$ или $$$3$$$. Будем обозначать длину строки $$$s$$$ как $$$|s|$$$. Для всех $$$i$$$ от $$$1$$$ до $$$|s|$$$ $$$i$$$-й символ строки $$$s$$$ обозначим как $$$s_i$$$.</p><p>Где-то в строке стоит курсор. Позиция курсора $$$\ell$$$ обозначается целым числом из множества $$$\{0, \ldots, |s|\}$$$, и имеет следующее значение: </p><ul> <li> если $$$\ell = 0$$$, тогда курсор расположен перед первым символом строки $$$s$$$. </li><li> если $$$\ell = |s|$$$, тогда курсор расположен после последнего символа строки $$$s$$$. </li><li> если $$$0 &lt; \ell &lt; |s|$$$, тогда курсор расположен между символами $$$s_\ell$$$ и $$$s_{\ell+1}$$$. </li></ul><p>Обозначим за $$$s_\text{left}$$$ строку, находящуюся левее курсора и за $$$s_\text{right}$$$ строку находящуюся правее курсора.</p><p>Также есть строка $$$c$$$, которая называется <span class="tex-font-style-underline">буфером</span>, которая изначально пуста. Всего существует три типа действий:</p><ul> <li> <span class="tex-font-style-bf">Передвижение</span>. Передвинуть курсор на один символ вправо. Это увеличивает $$$\ell$$$ на единицу. </li><li> <span class="tex-font-style-bf">Вырезание</span>. Присвоить $$$c \leftarrow s_\text{right}$$$, затем присвоить $$$s \leftarrow s_\text{left}$$$. </li><li> <span class="tex-font-style-bf">Вставка</span>. Добавить значение $$$c$$$ в конец строки $$$s$$$. Заметьте, что это никак не меняет $$$c$$$. </li></ul><p>Изначально курсор находится в позиции $$$\ell = 0$$$. Затем, исполняется следующая процедура:</p><ol> <li> Применить передвижение один раз. </li><li> Применить вырезание один раз. </li><li> Несколько применить вставку, количество раз равно $$$s_\ell$$$. </li><li> Если $$$\ell = x$$$, остановиться. Иначе, вернуться к шагу 1. </li></ol><p>Вам дана изначальная строка $$$s$$$ и целое число $$$x$$$. Какой будет длина строки $$$s$$$ когда процедура остановится? Так как это число может быть очень большим, выведите его остаток при делении на $$$10^9 + 7$$$. </p><p>Гарантируется, что $$$\ell \le |s|$$$ в любой момент времени.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 1000$$$), количество наборов входных данных. В следующих строках находятся их описания.</p><p>В первой строке каждого набора входных данных записано единственное целое число $$$x$$$ ($$$1 \le x \le 10^6$$$). Во второй строке находится изначальная строка $$$s$$$ ($$$1 \le |s| \le 500$$$). Гарантируется, что $$$s$$$ состоит только из символов «<span class="tex-font-style-tt">1</span>», «<span class="tex-font-style-tt">2</span>», «<span class="tex-font-style-tt">3</span>».</p><p>Гарантируется, что сумма $$$x$$$ по всем тестовым случаям не превосходит $$$10^6$$$. Гарантируется, что во всех тестовых случаях во время процедуры $$$\ell \le |s|$$$ в любой момент времени.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите остаток при делении длины строки после процедуры на $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 231 7 2323 6 333 24 133321333 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 25 1438 1101 686531475 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Давайте проиллюстрируем, что происходит в первом тестовом случае. Изначально у нас $$$s = $$$ <span class="tex-font-style-tt">231</span>. Изначально, $$$\ell = 0$$$ и $$$c = \varepsilon$$$ (пустая строка). Вот как изменяются эти значения в ходе процедуры:</p><ul><p> </p><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 1$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2</span> и $$$c = $$$ <span class="tex-font-style-tt">31</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">2</span> раза:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 1 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 2$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23</span> и $$$c = $$$ <span class="tex-font-style-tt">131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">3</span> раза:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 2 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим$$$\ell = 3$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">231</span> и $$$c = $$$ <span class="tex-font-style-tt">31131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">1</span> раз:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 3 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 4$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2313</span> и $$$c = $$$ <span class="tex-font-style-tt">1131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">3</span> раза:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2313113113111311311131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 4 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 5$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131</span> и $$$c = $$$ <span class="tex-font-style-tt">13113111311311131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">1</span> раз:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2313113113111311311131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 5 = x$$$, поэтому мы останавливаемся. </li></ul><p>В конце процедуры, $$$s$$$ имеет длину $$$25$$$. </p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:53:31</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'81249224fdaf9d90',t:'MTY5NjY2NTIxMS45NDYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1700"]
1280B
1280
B
ru
B. Beingawesomeism
<div class="problem-statement"><div class="header"><div class="title">B. Beingawesomeism</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы всемогущее существо и создали прямоугольный мир. Ваш мир настолько удобный, что может быть представлен в виде таблицы размером $$$r \times c$$$. Каждая клетка этой таблицы обозначает некоторую страну. Каждая страна принадлежит некоторой религии. Всего существует две религии в этом мире. Одна из религий называется Beingawesomeism, люди этой религии делают добрые поступки, чтобы быть хорошими. Другая религия называется Pushingittoofarism, люди этой религии совершают убийства, чтобы быть плохими.</p><p>На самом деле вы не абсолютно всемогущи. У вас есть только одна сила, которую вы можете применить бесконечное число раз! Ваша сила позволяет вам посылать миссионерские группы. Когда миссионерская группа из определенной страны, назовем ее $$$a$$$, приходит в другую страну $$$b$$$, она меняет религию страны $$$b$$$ на религию страны $$$a$$$.</p><p>Силу можно использовать следующим образом: </p><ul> <li> Вы выбираете горизонтальную полоску $$$1 \times x$$$ или вертикальную полоску $$$x \times 1$$$ внутри таблицы. Вы можете выбирать любое значение $$$x$$$; </li><li> Вы выбираете направление $$$d$$$. Если вы выбрали горизонтальную полоску, вы можете выбрать направления СЕВЕР или ЮГ. Если вы выбрали вертикальную полоску, вы можете выбрать направления ВОСТОК или ЗАПАД; </li><li> Вы выбираете количество шагов $$$s$$$; </li><li> Вы командуете каждой стране находящейся внутри выбранной полоски послать миссионерскую группу, которая пройдет $$$s$$$ шагов в направлении $$$d$$$. На каждом шаге, она посетит и возможно поменяет религию (способом описанным ранее) у всех $$$s$$$ стран на своем пути; </li><li> параметры $$$x$$$, $$$d$$$, $$$s$$$ можно выбирать такими, чтобы никакая миссионерская группа не вышла за пределы таблицы. </li></ul><p>Следующая картинка показывает один возможный способ использования силы. Здесь символ <span class="tex-font-style-tt">A</span> обозначает страну с религией Beingawesomeism и символ <span class="tex-font-style-tt">P</span> обозначает страну с религией Pushingittoofarism. Здесь мы выбрали горизонтальную полоску $$$1 \times 4$$$, направление СЕВЕР и количество шагов $$$s = 2$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/5417185338bfaae1779d2924b2c740f9987d6dc2.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Вы существо, которое верит в свободную волю каждого человека. Однако, вы хотите немедленно приостановить убийства. Таким образом вы решили использовать силу и попробовать сделать Beingawesomeism религией всех стран.</p><p>Какое минимальное количество применений силы требуется, чтобы сделать религией каждой страны Beingawesomeism?</p><p>Если это сделать невозможно, вы должны признать свой провал и сообщить об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>Первая строка каждого тестового случая содержит два целых числа $$$r$$$ и $$$c$$$, обозначающие размеры таблицы ($$$1 \le r, c \le 60$$$). Следующие $$$r$$$ строк содержат по $$$c$$$ символов, описывающих религии стран. $$$j$$$-й символ в $$$i$$$-й строке описывает религию страны в строке $$$i$$$ и столбце $$$j$$$. При этом:</p><ul> <li> символ «<span class="tex-font-style-tt">A</span>» означает, что религия Beingawesomeism; </li><li> символ «<span class="tex-font-style-tt">P</span>» означает, что религия Pushingittoofarism. </li></ul><p>Гарантируется, что все символы таблицы это «<span class="tex-font-style-tt">A</span>» или «<span class="tex-font-style-tt">P</span>». Гарантируется, что сумма $$$r \cdot c$$$ по всем тестовым случаям не превосходит $$$3 \cdot 10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите единственную строку, содержащую минимальное возможное количество использований силы нужное, чтобы сделать Beingawesomeism религией во всех странах. Если сделать Beingawesomeism религией во всех странах невозможно, выведите строку «<span class="tex-font-style-tt">MORTAL</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 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 MORTAL 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае можно добиться требуемого за два применения силы.</p><p>Первое использование:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8c0cf3491480a81d4f2affdc3a9cecd5754d45dd.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Второе использование:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/547386a217ca0c1da5e00b77f04b72c07c40b38d.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором тестовом случае можно добиться требуемого за одно применение силы.</p><p>В третьем тестовом случае невозможно сделать религией всех стран Beingawesomeism, поэтому ответ «<span class="tex-font-style-tt">MORTAL</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="f47eb254dcf5d8711666fb1cd7e4f512"/> <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="e32544b9cb685be4a903dab3307027ab419a190c"/> <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='f47eb254dcf5d8711666fb1cd7e4f512'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1280%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='f47eb254dcf5d8711666fb1cd7e4f512'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1280">Codeforces Round 607 (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='f47eb254dcf5d8711666fb1cd7e4f512'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1280/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='f47eb254dcf5d8711666fb1cd7e4f512'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="495761"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f47eb254dcf5d8711666fb1cd7e4f512'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="495761"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72165" title="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10064" resourceName="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" resourceManual="true" src="//codeforces.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/72212" title="Codeforces Round #607 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10080" resourceName="Codeforces Round #607 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/1280">Задачи</a></li> <li><a href="/contest/1280/submit">Отослать</a></li> <li><a href="/contest/1280/my">Мои посылки</a></li> <li><a href="/contest/1280/status">Статус</a></li> <li><a href="/contest/1280/hacks">Взломы</a></li> <li><a href="/contest/1280/room/1">Комната</a></li> <li><a href="/contest/1280/standings">Положение</a></li> <li><a href="/contest/1280/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e2b6180e9366029ceaa9722e3d109167def8877f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Beingawesomeism</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы всемогущее существо и создали прямоугольный мир. Ваш мир настолько удобный, что может быть представлен в виде таблицы размером $$$r \times c$$$. Каждая клетка этой таблицы обозначает некоторую страну. Каждая страна принадлежит некоторой религии. Всего существует две религии в этом мире. Одна из религий называется Beingawesomeism, люди этой религии делают добрые поступки, чтобы быть хорошими. Другая религия называется Pushingittoofarism, люди этой религии совершают убийства, чтобы быть плохими.</p><p>На самом деле вы не абсолютно всемогущи. У вас есть только одна сила, которую вы можете применить бесконечное число раз! Ваша сила позволяет вам посылать миссионерские группы. Когда миссионерская группа из определенной страны, назовем ее $$$a$$$, приходит в другую страну $$$b$$$, она меняет религию страны $$$b$$$ на религию страны $$$a$$$.</p><p>Силу можно использовать следующим образом: </p><ul> <li> Вы выбираете горизонтальную полоску $$$1 \times x$$$ или вертикальную полоску $$$x \times 1$$$ внутри таблицы. Вы можете выбирать любое значение $$$x$$$; </li><li> Вы выбираете направление $$$d$$$. Если вы выбрали горизонтальную полоску, вы можете выбрать направления СЕВЕР или ЮГ. Если вы выбрали вертикальную полоску, вы можете выбрать направления ВОСТОК или ЗАПАД; </li><li> Вы выбираете количество шагов $$$s$$$; </li><li> Вы командуете каждой стране находящейся внутри выбранной полоски послать миссионерскую группу, которая пройдет $$$s$$$ шагов в направлении $$$d$$$. На каждом шаге, она посетит и возможно поменяет религию (способом описанным ранее) у всех $$$s$$$ стран на своем пути; </li><li> параметры $$$x$$$, $$$d$$$, $$$s$$$ можно выбирать такими, чтобы никакая миссионерская группа не вышла за пределы таблицы. </li></ul><p>Следующая картинка показывает один возможный способ использования силы. Здесь символ <span class="tex-font-style-tt">A</span> обозначает страну с религией Beingawesomeism и символ <span class="tex-font-style-tt">P</span> обозначает страну с религией Pushingittoofarism. Здесь мы выбрали горизонтальную полоску $$$1 \times 4$$$, направление СЕВЕР и количество шагов $$$s = 2$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/5417185338bfaae1779d2924b2c740f9987d6dc2.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Вы существо, которое верит в свободную волю каждого человека. Однако, вы хотите немедленно приостановить убийства. Таким образом вы решили использовать силу и попробовать сделать Beingawesomeism религией всех стран.</p><p>Какое минимальное количество применений силы требуется, чтобы сделать религией каждой страны Beingawesomeism?</p><p>Если это сделать невозможно, вы должны признать свой провал и сообщить об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>Первая строка каждого тестового случая содержит два целых числа $$$r$$$ и $$$c$$$, обозначающие размеры таблицы ($$$1 \le r, c \le 60$$$). Следующие $$$r$$$ строк содержат по $$$c$$$ символов, описывающих религии стран. $$$j$$$-й символ в $$$i$$$-й строке описывает религию страны в строке $$$i$$$ и столбце $$$j$$$. При этом:</p><ul> <li> символ «<span class="tex-font-style-tt">A</span>» означает, что религия Beingawesomeism; </li><li> символ «<span class="tex-font-style-tt">P</span>» означает, что религия Pushingittoofarism. </li></ul><p>Гарантируется, что все символы таблицы это «<span class="tex-font-style-tt">A</span>» или «<span class="tex-font-style-tt">P</span>». Гарантируется, что сумма $$$r \cdot c$$$ по всем тестовым случаям не превосходит $$$3 \cdot 10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите единственную строку, содержащую минимальное возможное количество использований силы нужное, чтобы сделать Beingawesomeism религией во всех странах. Если сделать Beingawesomeism религией во всех странах невозможно, выведите строку «<span class="tex-font-style-tt">MORTAL</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 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 MORTAL 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае можно добиться требуемого за два применения силы.</p><p>Первое использование:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8c0cf3491480a81d4f2affdc3a9cecd5754d45dd.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Второе использование:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/547386a217ca0c1da5e00b77f04b72c07c40b38d.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором тестовом случае можно добиться требуемого за одно применение силы.</p><p>В третьем тестовом случае невозможно сделать религией всех стран Beingawesomeism, поэтому ответ «<span class="tex-font-style-tt">MORTAL</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:53: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:'8124922e5a887b3b',t:'MTY5NjY2NTIxMy41NDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1800"]
1280C
1280
C
ru
C. Jeremy Bearimy
<div class="problem-statement"><div class="header"><div class="title">C. Jeremy Bearimy</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Добро пожаловать! Все хорошо.</p><p>Вы прибыли в Среднее место, место между Хорошим местом и Плохим местом. Вам поручено выполнить два задания, одно сделает всех людей счастливыми, другое будет мучить их вечно.</p><p>У вас есть список $$$k$$$ пар людей, которые прибыли в новый район. Вам нужно назначить каждому из $$$2k$$$ людей свой из $$$2k$$$ домов. Каждый человек будет владельцем ровно одного дома и каждый дом будет иметь ровно одного владельца.</p><p>Конечно, в этом районе можно перемещаться между домами. Всего есть $$$2k - 1$$$ дорога, каждая из них соединяет два дома. Требуется некоторое время, чтобы проехать по дороге. Эти времена известны для каждой дороги. Район спроектирован таким образом, что между любыми двумя домами существует ровно один путь по дорогам от одного дома до другого, не проходящий по одной и той же дороге дважды. Другими словами, граф, в котором вершины это дома, а ребра это дороги это дерево.</p><p>Люди в каждой из $$$k$$$ пар людей хорошо дружат и любят ходить в гости. Мы пронумеруем пары людей от $$$1$$$ до $$$k$$$. Обозначим за $$$f(i)$$$ время, которое требуется $$$i$$$-й паре людей, чтобы проехать между домами друг друга.</p><p>Как уже было сказано ранее, вы должны сопоставить каждому из $$$2k$$$ людей один из $$$2k$$$ домов. У вас есть две миссии, одна назначена из Хорошего места, другая назначена из Плохого места. Эти миссии заключаются в следующем:</p><ul> <li> Первая миссия, из Хорошего места, заключается в том, чтобы сопоставить людям дома, так чтобы сумма $$$f(i)$$$ по всем парам $$$i$$$ была минимальна. Давайте обозначим эту минимальную возможную сумму за $$$G$$$. Это дает нам уверенность, что все пары друзей могут легко и эффективно посещать друг друга; </li><li> Вторая миссия, из Плохого места, заключается в том, чтобы сопоставить людям дома, так чтобы сумма $$$f(i)$$$ по всем парам $$$i$$$ была максимальна. Давайте обозначим эту максимальную возможную сумму за $$$B$$$. Это дает нам уверенность, что все пары друзей могут только трудно и неэффективно посещать друг друга; </li></ul><p>Чему равны значения $$$G$$$ и $$$B$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 500$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>Первая строка каждого тестового случая содержит единственное целое число $$$k$$$, обозначающая количество пар людей ($$$1 \le k \le 10^5$$$). В следующих $$$2k - 1$$$ строках находится описание дорог; в $$$i$$$-й строке находится три целых числа $$$a_i, b_i, t_i$$$, которые обозначают, что $$$i$$$-я дорога соединяет дома $$$a_i$$$ и $$$b_i$$$ и требует $$$t_i$$$ единиц времени, чтобы проехать по ней ($$$1 \le a_i, b_i \le 2k$$$, $$$a_i \neq b_i$$$, $$$1 \le t_i \le 10^6$$$). Гарантируется, что данные дороги образуют структуру дерева.</p><p>Гарантируется, что сумма всех $$$k$$$ по всем тестовым случаям не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите два целых числа $$$G$$$ и $$$B$$$, разделенные пробелом.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 1 2 3 3 2 4 2 4 3 4 5 6 5 6 5 2 1 2 1 1 3 2 1 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 33 6 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого тестового случая, мы можем получить минимальную сумму равную $$$G = 15$$$. Один из способов достичь такую сумму это следующее назначение домов:</p><ul> <li> Первой паре людей назначим дома $$$5$$$ и $$$6$$$, что даст нам $$$f(1) = 5$$$; </li><li> Второй паре людей назначим дома $$$1$$$ и $$$4$$$, что даст нам $$$f(2) = 6$$$; </li><li> Третьей паре людей назначим дома $$$3$$$ и $$$2$$$, что даст нам $$$f(3) = 4$$$. </li></ul><p>Обратите внимание, что тогда сумма всех $$$f(i)$$$ это $$$5 + 6 + 4 = 15$$$. </p><p>Также мы можем получить максимальную сумму равной $$$B = 33$$$. Один из способов достичь такую сумму это следующее назначение домов:</p><ul> <li> Первой паре людей назначим дома $$$1$$$ и $$$4$$$, что даст нам $$$f(1) = 6$$$; </li><li> Второй паре людей назначим дома $$$6$$$ и $$$2$$$, что даст нам $$$f(2) = 14$$$; </li><li> Третьей паре людей назначим дома $$$3$$$ и $$$5$$$, что даст нам $$$f(3) = 13$$$. </li></ul><p>Обратите внимание, что тогда сумма всех $$$f(i)$$$ это $$$6 + 14 + 13 = 33$$$. </p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="62dece52fedf2fb2bc110f4f31ede51a"/> <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="e32544b9cb685be4a903dab3307027ab419a190c"/> <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='62dece52fedf2fb2bc110f4f31ede51a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1280%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='62dece52fedf2fb2bc110f4f31ede51a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1280">Codeforces Round 607 (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='62dece52fedf2fb2bc110f4f31ede51a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1280/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='62dece52fedf2fb2bc110f4f31ede51a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="495762"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='62dece52fedf2fb2bc110f4f31ede51a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="495762"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72165" title="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10064" resourceName="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" resourceManual="true" src="//codeforces.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/72212" title="Codeforces Round #607 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10080" resourceName="Codeforces Round #607 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/1280">Задачи</a></li> <li><a href="/contest/1280/submit">Отослать</a></li> <li><a href="/contest/1280/my">Мои посылки</a></li> <li><a href="/contest/1280/status">Статус</a></li> <li><a href="/contest/1280/hacks">Взломы</a></li> <li><a href="/contest/1280/room/1">Комната</a></li> <li><a href="/contest/1280/standings">Положение</a></li> <li><a href="/contest/1280/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ba88554c490c70e7b60054dd58db8b82d7a41965"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Jeremy Bearimy</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Добро пожаловать! Все хорошо.</p><p>Вы прибыли в Среднее место, место между Хорошим местом и Плохим местом. Вам поручено выполнить два задания, одно сделает всех людей счастливыми, другое будет мучить их вечно.</p><p>У вас есть список $$$k$$$ пар людей, которые прибыли в новый район. Вам нужно назначить каждому из $$$2k$$$ людей свой из $$$2k$$$ домов. Каждый человек будет владельцем ровно одного дома и каждый дом будет иметь ровно одного владельца.</p><p>Конечно, в этом районе можно перемещаться между домами. Всего есть $$$2k - 1$$$ дорога, каждая из них соединяет два дома. Требуется некоторое время, чтобы проехать по дороге. Эти времена известны для каждой дороги. Район спроектирован таким образом, что между любыми двумя домами существует ровно один путь по дорогам от одного дома до другого, не проходящий по одной и той же дороге дважды. Другими словами, граф, в котором вершины это дома, а ребра это дороги это дерево.</p><p>Люди в каждой из $$$k$$$ пар людей хорошо дружат и любят ходить в гости. Мы пронумеруем пары людей от $$$1$$$ до $$$k$$$. Обозначим за $$$f(i)$$$ время, которое требуется $$$i$$$-й паре людей, чтобы проехать между домами друг друга.</p><p>Как уже было сказано ранее, вы должны сопоставить каждому из $$$2k$$$ людей один из $$$2k$$$ домов. У вас есть две миссии, одна назначена из Хорошего места, другая назначена из Плохого места. Эти миссии заключаются в следующем:</p><ul> <li> Первая миссия, из Хорошего места, заключается в том, чтобы сопоставить людям дома, так чтобы сумма $$$f(i)$$$ по всем парам $$$i$$$ была минимальна. Давайте обозначим эту минимальную возможную сумму за $$$G$$$. Это дает нам уверенность, что все пары друзей могут легко и эффективно посещать друг друга; </li><li> Вторая миссия, из Плохого места, заключается в том, чтобы сопоставить людям дома, так чтобы сумма $$$f(i)$$$ по всем парам $$$i$$$ была максимальна. Давайте обозначим эту максимальную возможную сумму за $$$B$$$. Это дает нам уверенность, что все пары друзей могут только трудно и неэффективно посещать друг друга; </li></ul><p>Чему равны значения $$$G$$$ и $$$B$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 500$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>Первая строка каждого тестового случая содержит единственное целое число $$$k$$$, обозначающая количество пар людей ($$$1 \le k \le 10^5$$$). В следующих $$$2k - 1$$$ строках находится описание дорог; в $$$i$$$-й строке находится три целых числа $$$a_i, b_i, t_i$$$, которые обозначают, что $$$i$$$-я дорога соединяет дома $$$a_i$$$ и $$$b_i$$$ и требует $$$t_i$$$ единиц времени, чтобы проехать по ней ($$$1 \le a_i, b_i \le 2k$$$, $$$a_i \neq b_i$$$, $$$1 \le t_i \le 10^6$$$). Гарантируется, что данные дороги образуют структуру дерева.</p><p>Гарантируется, что сумма всех $$$k$$$ по всем тестовым случаям не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите два целых числа $$$G$$$ и $$$B$$$, разделенные пробелом.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 1 2 3 3 2 4 2 4 3 4 5 6 5 6 5 2 1 2 1 1 3 2 1 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 33 6 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого тестового случая, мы можем получить минимальную сумму равную $$$G = 15$$$. Один из способов достичь такую сумму это следующее назначение домов:</p><ul> <li> Первой паре людей назначим дома $$$5$$$ и $$$6$$$, что даст нам $$$f(1) = 5$$$; </li><li> Второй паре людей назначим дома $$$1$$$ и $$$4$$$, что даст нам $$$f(2) = 6$$$; </li><li> Третьей паре людей назначим дома $$$3$$$ и $$$2$$$, что даст нам $$$f(3) = 4$$$. </li></ul><p>Обратите внимание, что тогда сумма всех $$$f(i)$$$ это $$$5 + 6 + 4 = 15$$$. </p><p>Также мы можем получить максимальную сумму равной $$$B = 33$$$. Один из способов достичь такую сумму это следующее назначение домов:</p><ul> <li> Первой паре людей назначим дома $$$1$$$ и $$$4$$$, что даст нам $$$f(1) = 6$$$; </li><li> Второй паре людей назначим дома $$$6$$$ и $$$2$$$, что даст нам $$$f(2) = 14$$$; </li><li> Третьей паре людей назначим дома $$$3$$$ и $$$5$$$, что даст нам $$$f(3) = 13$$$. </li></ul><p>Обратите внимание, что тогда сумма всех $$$f(i)$$$ это $$$6 + 14 + 13 = 33$$$. </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:53:34</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'812492385ca275a7',t:'MTY5NjY2NTIxNC45NDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2000"]
1280D
1280
D
ru
D. Мисс Punyverse
<div class="problem-statement"><div class="header"><div class="title">D. Мисс Punyverse</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дуб имеет $$$n$$$ гнезд, пронумерованных целыми числами от $$$1$$$ до $$$n$$$. Гнездо $$$i$$$ это дом для $$$b_i$$$ пчел и $$$w_i$$$ ос.</p><p>Некоторые гнезда соединены ветками. Мы называем два гнезда <span class="tex-font-style-underline">соседними</span> если существует ветка, соединяющая их. <span class="tex-font-style-underline">Простой путь</span> из гнезда $$$x$$$ в $$$y$$$ задается последовательностью $$$s_0, \ldots, s_p$$$ различных гнезд, где $$$p$$$ это неотрицательное целое число и $$$s_0 = x$$$, $$$s_p = y$$$ и $$$s_{i-1}$$$ и $$$s_{i}$$$ соседние для всех $$$i = 1, \ldots, p$$$. Ветки дуба расположены так, что для любой пары гнезд $$$x$$$ и $$$y$$$ существует единственный простой путь из $$$x$$$ в $$$y$$$. По причине этого и биологи и программисты согласны, что дуб, по факту, является деревом.</p><p><span class="tex-font-style-underline">Деревня</span> это <span class="tex-font-style-underline">непустое</span> множество $$$V$$$ гнезд, такое что для всех $$$x$$$ и $$$y$$$ из $$$V$$$, существует простой путь из $$$x$$$ в $$$y$$$, все гнезда вдоль которого также лежат в $$$V$$$.</p><p>Множество деревень $$$\cal P$$$ называется <span class="tex-font-style-underline">разбиением</span> если каждое из $$$n$$$ гнезд содержится в ровно одной деревне из $$$\cal P$$$. Другими словами, никакие две деревни из $$$\cal P$$$ не содержат одно и то же гнездо и в объединении дают все $$$n$$$ гнезд.</p><p>На дубе проводится ежегодный конкурс красоты мисс Punyverse. Всего два участника участвуют в этом году, это некрасивая оса и красивая пчела. Победитель конкурса красоты определяется голосованием, систему которого мы сейчас опишем. Пусть $$$\mathcal{P}$$$ это разбиение гнезд на $$$m$$$ деревень $$$V_1, \ldots, V_m$$$. Проводится локальные выборы в каждой деревне. Каждое насекомое в деревне голосует за свое любимое насекомое. Если в деревне окажется, что <span class="tex-font-style-bf">строго</span> больше голосов отдано за некрасивую осу чем за красивую пчелу, тогда некрасивая оса объявляется <span class="tex-font-style-it">победителем</span> в этой деревне. Иначе, красивая пчела <span class="tex-font-style-it">побеждает</span>.</p><p>Известно, что пчелы всегда голосуют за пчел, то есть проголосуют за красивую пчелу в этом году и осы всегда голосуют за ос, то есть проголосуют за некрасивую осу в этом году. Все насекомые в улье участвуют в голосовании.</p><p>Мэр Waspacito, а также его заместитель Alexwasp, хотят, чтобы некрасивая оса победила. Они имеют влияние и могут выбрать разбиение дуба на ровно $$$m$$$ деревень. Если они выберут разбиение оптимально, определите максимальное количество деревень, в которых победит некрасивая оса.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 100$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>В первой строке каждого тестового случая находится два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le m \le n \le 3000$$$). Во второй строке находится $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \le b_i \le 10^9$$$). В третьей строке находится $$$n$$$ целых чисел $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \le w_i \le 10^9$$$). В следующих $$$n - 1$$$ находятся описания соседних пар гнезд, $$$i$$$-я из них содержит два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \neq y_i$$$), обозначающих номера гнезд, соединенных веткой. Гарантируется, что эти пары задают дерево.</p><p>Гарантируется, что сумма $$$n$$$ по всем тестовым случаям не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите целое число, равное максимальному количеству деревень, в которых победит некрасивая оса по всем разбиениям дуба на $$$m$$$ деревень.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 3 10 160 70 50 70 111 111 0 1 2 2 3 3 4 2 1 143 420 214 349 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, нужно разделить $$$n = 4$$$ гнезд на $$$m = 3$$$ деревень. Мы можем так разделить, что некрасивая оса победит в $$$2$$$ деревнях, например с помощью такого разбиения: $$$\{\{1, 2\}, \{3\}, \{4\}\}$$$. В этом разбиении:</p><ul> <li> Некрасивая оса побеждает в деревне $$$\{1, 2\}$$$, получив $$$181$$$ голосов тогда как красивая пчела получила $$$170$$$ голосов; </li><li> Некрасивая оса также побеждает в деревне $$$\{3\}$$$, получив $$$111$$$ голосов тогда как красивая пчела получила $$$70$$$ голосов; </li><li> Некрасивая оса проиграет в деревне $$$\{4\}$$$, получив $$$0$$$ голосов тогда как красивая пчела получила $$$50$$$. </li></ul><p>Таким образом некрасивая оса победила в $$$2$$$ деревнях и можно показать, что это максимально возможное число.</p><p>Во втором тесте мы должны разделить $$$n = 2$$$ гнезд на $$$m = 1$$$ деревень. Есть только один способ это сделать: $$$\{\{1, 2\}\}$$$. В этом разбиении некрасивая оса получит $$$563$$$ голосов и красивая пчела также получит $$$563$$$ голосов. Некрасивая оса побеждает, если получает строго больше голосов. Поэтому некрасивая оса не выиграет ни в какой деревне.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="df2cc77b2726255fa6ec518d0e5bf51b"/> <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="e32544b9cb685be4a903dab3307027ab419a190c"/> <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='df2cc77b2726255fa6ec518d0e5bf51b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1280%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='df2cc77b2726255fa6ec518d0e5bf51b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1280">Codeforces Round 607 (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='df2cc77b2726255fa6ec518d0e5bf51b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1280/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='df2cc77b2726255fa6ec518d0e5bf51b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="495763"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='df2cc77b2726255fa6ec518d0e5bf51b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="495763"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72165" title="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10064" resourceName="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" resourceManual="true" src="//codeforces.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/72212" title="Codeforces Round #607 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10080" resourceName="Codeforces Round #607 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/1280">Задачи</a></li> <li><a href="/contest/1280/submit">Отослать</a></li> <li><a href="/contest/1280/my">Мои посылки</a></li> <li><a href="/contest/1280/status">Статус</a></li> <li><a href="/contest/1280/hacks">Взломы</a></li> <li><a href="/contest/1280/room/1">Комната</a></li> <li><a href="/contest/1280/standings">Положение</a></li> <li><a href="/contest/1280/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5427fce018104ffdb518c9dbdbc713d6410342ac"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Мисс Punyverse</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дуб имеет $$$n$$$ гнезд, пронумерованных целыми числами от $$$1$$$ до $$$n$$$. Гнездо $$$i$$$ это дом для $$$b_i$$$ пчел и $$$w_i$$$ ос.</p><p>Некоторые гнезда соединены ветками. Мы называем два гнезда <span class="tex-font-style-underline">соседними</span> если существует ветка, соединяющая их. <span class="tex-font-style-underline">Простой путь</span> из гнезда $$$x$$$ в $$$y$$$ задается последовательностью $$$s_0, \ldots, s_p$$$ различных гнезд, где $$$p$$$ это неотрицательное целое число и $$$s_0 = x$$$, $$$s_p = y$$$ и $$$s_{i-1}$$$ и $$$s_{i}$$$ соседние для всех $$$i = 1, \ldots, p$$$. Ветки дуба расположены так, что для любой пары гнезд $$$x$$$ и $$$y$$$ существует единственный простой путь из $$$x$$$ в $$$y$$$. По причине этого и биологи и программисты согласны, что дуб, по факту, является деревом.</p><p><span class="tex-font-style-underline">Деревня</span> это <span class="tex-font-style-underline">непустое</span> множество $$$V$$$ гнезд, такое что для всех $$$x$$$ и $$$y$$$ из $$$V$$$, существует простой путь из $$$x$$$ в $$$y$$$, все гнезда вдоль которого также лежат в $$$V$$$.</p><p>Множество деревень $$$\cal P$$$ называется <span class="tex-font-style-underline">разбиением</span> если каждое из $$$n$$$ гнезд содержится в ровно одной деревне из $$$\cal P$$$. Другими словами, никакие две деревни из $$$\cal P$$$ не содержат одно и то же гнездо и в объединении дают все $$$n$$$ гнезд.</p><p>На дубе проводится ежегодный конкурс красоты мисс Punyverse. Всего два участника участвуют в этом году, это некрасивая оса и красивая пчела. Победитель конкурса красоты определяется голосованием, систему которого мы сейчас опишем. Пусть $$$\mathcal{P}$$$ это разбиение гнезд на $$$m$$$ деревень $$$V_1, \ldots, V_m$$$. Проводится локальные выборы в каждой деревне. Каждое насекомое в деревне голосует за свое любимое насекомое. Если в деревне окажется, что <span class="tex-font-style-bf">строго</span> больше голосов отдано за некрасивую осу чем за красивую пчелу, тогда некрасивая оса объявляется <span class="tex-font-style-it">победителем</span> в этой деревне. Иначе, красивая пчела <span class="tex-font-style-it">побеждает</span>.</p><p>Известно, что пчелы всегда голосуют за пчел, то есть проголосуют за красивую пчелу в этом году и осы всегда голосуют за ос, то есть проголосуют за некрасивую осу в этом году. Все насекомые в улье участвуют в голосовании.</p><p>Мэр Waspacito, а также его заместитель Alexwasp, хотят, чтобы некрасивая оса победила. Они имеют влияние и могут выбрать разбиение дуба на ровно $$$m$$$ деревень. Если они выберут разбиение оптимально, определите максимальное количество деревень, в которых победит некрасивая оса.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 100$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>В первой строке каждого тестового случая находится два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le m \le n \le 3000$$$). Во второй строке находится $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \le b_i \le 10^9$$$). В третьей строке находится $$$n$$$ целых чисел $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \le w_i \le 10^9$$$). В следующих $$$n - 1$$$ находятся описания соседних пар гнезд, $$$i$$$-я из них содержит два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \neq y_i$$$), обозначающих номера гнезд, соединенных веткой. Гарантируется, что эти пары задают дерево.</p><p>Гарантируется, что сумма $$$n$$$ по всем тестовым случаям не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите целое число, равное максимальному количеству деревень, в которых победит некрасивая оса по всем разбиениям дуба на $$$m$$$ деревень.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 3 10 160 70 50 70 111 111 0 1 2 2 3 3 4 2 1 143 420 214 349 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, нужно разделить $$$n = 4$$$ гнезд на $$$m = 3$$$ деревень. Мы можем так разделить, что некрасивая оса победит в $$$2$$$ деревнях, например с помощью такого разбиения: $$$\{\{1, 2\}, \{3\}, \{4\}\}$$$. В этом разбиении:</p><ul> <li> Некрасивая оса побеждает в деревне $$$\{1, 2\}$$$, получив $$$181$$$ голосов тогда как красивая пчела получила $$$170$$$ голосов; </li><li> Некрасивая оса также побеждает в деревне $$$\{3\}$$$, получив $$$111$$$ голосов тогда как красивая пчела получила $$$70$$$ голосов; </li><li> Некрасивая оса проиграет в деревне $$$\{4\}$$$, получив $$$0$$$ голосов тогда как красивая пчела получила $$$50$$$. </li></ul><p>Таким образом некрасивая оса победила в $$$2$$$ деревнях и можно показать, что это максимально возможное число.</p><p>Во втором тесте мы должны разделить $$$n = 2$$$ гнезд на $$$m = 1$$$ деревень. Есть только один способ это сделать: $$$\{\{1, 2\}\}$$$. В этом разбиении некрасивая оса получит $$$563$$$ голосов и красивая пчела также получит $$$563$$$ голосов. Некрасивая оса побеждает, если получает строго больше голосов. Поэтому некрасивая оса не выиграет ни в какой деревне.</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:53: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:'812492411c2676b5',t:'MTY5NjY2NTIxNi40MTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*2500"]
1280E
1280
E
ru
E. Потери Кирхгофа
<div class="problem-statement"><div class="header"><div class="title">E. Потери Кирхгофа</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Ваш друг Кирхгоф был шокирован текущим состоянием в дизайне электрических схем.</p><p>«Боже мой! Что не так с этой областью? Все эти цепи неэффективны! Есть столько возможностей для улучшения. Эти цепи имеют слишком большое полное сопротивление. Почему они сделаны таким образом? Это просто вызывает массовую потерю резисторов! Вся их область могла бы сэкономить так много денег, если бы они просто максимизировали потенциал своих цепей. Почему они не могут просто попробовать альтернативные идеи? Это абсолютно отвратительно» сказал он.</p><p>Он очень недоволен ситуацией, но даже после стольких жалоб он все еще не имеет возможности напрямую что-то изменить.</p><p>Частота его протестов по поводу электротехники вам надоела, поэтому вы решили взять на себя ответственность и помочь ему самостоятельно. Вы планируете создать программу, которая будет оптимизировать схемы, не меняя при этом схему и сопротивление.</p><p><span class="tex-font-style-underline">Цепь</span> имеет два конца и соотносится с некоторым параметром $$$R$$$ для этой цепи, который называется <span class="tex-font-style-bf">сопротивлением</span>.</p><p>Цепи, которые мы будем рассматривать будут получены из резисторов. Несколько цепей, среди которых могут быть резисторы, можно соединить вместе <span class="tex-font-style-underline">последовательно</span> или <span class="tex-font-style-underline">параллельно</span>, образуя более сложную цепь. Приведенная картинка изображает последовательное и параллельное соединения.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0e1d7a69b33fb326d5f7e3de6a52b2080b696820.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>По правилам вашего друга Киргхофа сопротивление может быть легко вычислено при соединении цепей в более сложную цепь следующим способом:</p><ul> <li> Когда соединяется $$$k$$$ цепей <span class="tex-font-style-underline">последовательно</span> с сопротивлениями $$$R_1, R_2, \ldots, R_k$$$, тогда сопротивление $$$R$$$ получившейся цепи будет суммой сопротивлений составляющих ее цепей $$$$$$R = R_1 + R_2 + \ldots + R_k.$$$$$$<p> </p></li><li> Когда соединяется $$$k$$$ цепей <span class="tex-font-style-underline">параллельно</span> с сопротивлениями $$$R_1, R_2, \ldots, R_k$$$, тогда сопротивление $$$R$$$ получившейся цепи будет получаться из следующего соотношения на $$$R$$$ $$$$$$\frac{1}{R} = \frac{1}{R_1} + \frac{1}{R_2} + \ldots + \frac{1}{R_k},$$$$$$ <span class="tex-font-style-underline">если все $$$R_i &gt; 0$$$</span>; если хотя бы одно из $$$R_i = 0$$$, тогда сопротивление получившейся цепи получается равным $$$R = 0$$$. </li></ul><p>Цепи будут представлены как строки. Резисторы представляются символом звездочки «<span class="tex-font-style-tt">*</span>». Для более сложных формул, обозначим строки $$$s_1, s_2, \ldots, s_k$$$, которые представляют $$$k \ge 2$$$ цепей. Тогда</p><ul> <li> строка «<span class="tex-font-style-tt">($$$s_1$$$ S $$$s_2$$$ S $$$\ldots$$$ S $$$s_k$$$)</span>» представляет их <span class="tex-font-style-underline">последовательное</span> соединение; </li><li> строка «<span class="tex-font-style-tt">($$$s_1$$$ P $$$s_2$$$ P $$$\ldots$$$ P $$$s_k$$$)</span>» представляет их <span class="tex-font-style-underline">параллельное</span> соединение. </li></ul><p>Например, строка «<span class="tex-font-style-tt">(* P (* S *) P *)</span>» представляет такую цепь:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/20aa87fefe6adf3989884422c259a4596d9e48d4.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Дана цепь. Ваша задача сопоставить сопротивления всем резисторам, так чтобы были выполнены следующие требования:</p><ul> <li> Каждому резистору сопоставлено <span class="tex-font-style-underline">неотрицательное целое</span> сопротивление; </li><li> Сопротивление всей цепи равно $$$r$$$; </li><li> Сумма сопротивлений всех резисторов минимально возможная. </li></ul><p>Если в схеме есть $$$n$$$ резисторов, то вам нужно найти список $$$r_1, r_2, \ldots, r_n$$$ ($$$0 \le r_i$$$, $$$r_i$$$ целое число), где $$$r_i$$$ это сопротивление сопоставленное $$$i$$$-у резистору в строке (слева направо), представляющей данную цепь. Если сделать сопоставление, в котором все условия выполнены невозможно, то сообщите об этом.</p><p>Если это сделать возможно, гарантируется, что минимальная сумма сопротивлений всех резисторов не превосходит $$$10^{18}$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 32000$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>Для каждого тестового случая в единственной строке находится целое число $$$r$$$ ($$$1 \le r \le 10^6$$$), пробел а затем строка, которая представляет некоторую цепь. Гарантируется, что эта строка корректна по определениям из условия задачи и действительно представляет некоторую цепь. Количество резисторов (символов равных «<span class="tex-font-style-tt">*</span>») не меньше, чем $$$1$$$ и не больше, чем $$$80000$$$.</p><p>Гарантируется что суммарное количество резисторов по всем тестовым случаям не превосходит $$$320000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите ответ:</p><ul> <li> Если возможно получить сопротивление данной цепи, равное $$$r$$$, выведите «<span class="tex-font-style-tt">REVOLTING</span>» (без кавычек) и затем $$$n$$$ неотрицательных целых чисел $$$r_1, r_2, \ldots, r_n$$$ — сопротивления сопоставленные резисторам. Здесь $$$n$$$ обозначает количество резисторов в цепи.<p> Если существует несколько возможных сопоставлений с минимальной суммой сопротивлений резисторов, вы можете найти любое из них;</p><p> </p></li><li> Если это невозможно выведите единственную строку: «<span class="tex-font-style-tt">LOSS</span>» (без кавычек). </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 * 1 (* S *) 1 (* P (* S *)) </pre></div><div class="output"><div class="title">Выходные данные</div><pre> REVOLTING 5 REVOLTING 1 0 REVOLTING 2 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Эта картинка иллюстрирует третий тестовый случай:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/228fdf51e9ffa6c9dcf58356af80229d8243dba9.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Здесь сумма сопротивлений всех резисторов равна $$$2 + 1 + 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="5b069f3f3a792b0d9c3bce43903a679b"/> <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="e32544b9cb685be4a903dab3307027ab419a190c"/> <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='5b069f3f3a792b0d9c3bce43903a679b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1280%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='5b069f3f3a792b0d9c3bce43903a679b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1280">Codeforces Round 607 (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='5b069f3f3a792b0d9c3bce43903a679b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1280/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2900 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5b069f3f3a792b0d9c3bce43903a679b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="495764"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5b069f3f3a792b0d9c3bce43903a679b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="495764"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72165" title="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10064" resourceName="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" resourceManual="true" src="//codeforces.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/72212" title="Codeforces Round #607 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10080" resourceName="Codeforces Round #607 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/1280">Задачи</a></li> <li><a href="/contest/1280/submit">Отослать</a></li> <li><a href="/contest/1280/my">Мои посылки</a></li> <li><a href="/contest/1280/status">Статус</a></li> <li><a href="/contest/1280/hacks">Взломы</a></li> <li><a href="/contest/1280/room/1">Комната</a></li> <li><a href="/contest/1280/standings">Положение</a></li> <li><a href="/contest/1280/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_16e48325232023ce88a9d3c2c0a23fee6aaf8c1a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Потери Кирхгофа</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Ваш друг Кирхгоф был шокирован текущим состоянием в дизайне электрических схем.</p><p>«Боже мой! Что не так с этой областью? Все эти цепи неэффективны! Есть столько возможностей для улучшения. Эти цепи имеют слишком большое полное сопротивление. Почему они сделаны таким образом? Это просто вызывает массовую потерю резисторов! Вся их область могла бы сэкономить так много денег, если бы они просто максимизировали потенциал своих цепей. Почему они не могут просто попробовать альтернативные идеи? Это абсолютно отвратительно» сказал он.</p><p>Он очень недоволен ситуацией, но даже после стольких жалоб он все еще не имеет возможности напрямую что-то изменить.</p><p>Частота его протестов по поводу электротехники вам надоела, поэтому вы решили взять на себя ответственность и помочь ему самостоятельно. Вы планируете создать программу, которая будет оптимизировать схемы, не меняя при этом схему и сопротивление.</p><p><span class="tex-font-style-underline">Цепь</span> имеет два конца и соотносится с некоторым параметром $$$R$$$ для этой цепи, который называется <span class="tex-font-style-bf">сопротивлением</span>.</p><p>Цепи, которые мы будем рассматривать будут получены из резисторов. Несколько цепей, среди которых могут быть резисторы, можно соединить вместе <span class="tex-font-style-underline">последовательно</span> или <span class="tex-font-style-underline">параллельно</span>, образуя более сложную цепь. Приведенная картинка изображает последовательное и параллельное соединения.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0e1d7a69b33fb326d5f7e3de6a52b2080b696820.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>По правилам вашего друга Киргхофа сопротивление может быть легко вычислено при соединении цепей в более сложную цепь следующим способом:</p><ul> <li> Когда соединяется $$$k$$$ цепей <span class="tex-font-style-underline">последовательно</span> с сопротивлениями $$$R_1, R_2, \ldots, R_k$$$, тогда сопротивление $$$R$$$ получившейся цепи будет суммой сопротивлений составляющих ее цепей $$$$$$R = R_1 + R_2 + \ldots + R_k.$$$$$$<p> </p></li><li> Когда соединяется $$$k$$$ цепей <span class="tex-font-style-underline">параллельно</span> с сопротивлениями $$$R_1, R_2, \ldots, R_k$$$, тогда сопротивление $$$R$$$ получившейся цепи будет получаться из следующего соотношения на $$$R$$$ $$$$$$\frac{1}{R} = \frac{1}{R_1} + \frac{1}{R_2} + \ldots + \frac{1}{R_k},$$$$$$ <span class="tex-font-style-underline">если все $$$R_i &gt; 0$$$</span>; если хотя бы одно из $$$R_i = 0$$$, тогда сопротивление получившейся цепи получается равным $$$R = 0$$$. </li></ul><p>Цепи будут представлены как строки. Резисторы представляются символом звездочки «<span class="tex-font-style-tt">*</span>». Для более сложных формул, обозначим строки $$$s_1, s_2, \ldots, s_k$$$, которые представляют $$$k \ge 2$$$ цепей. Тогда</p><ul> <li> строка «<span class="tex-font-style-tt">($$$s_1$$$ S $$$s_2$$$ S $$$\ldots$$$ S $$$s_k$$$)</span>» представляет их <span class="tex-font-style-underline">последовательное</span> соединение; </li><li> строка «<span class="tex-font-style-tt">($$$s_1$$$ P $$$s_2$$$ P $$$\ldots$$$ P $$$s_k$$$)</span>» представляет их <span class="tex-font-style-underline">параллельное</span> соединение. </li></ul><p>Например, строка «<span class="tex-font-style-tt">(* P (* S *) P *)</span>» представляет такую цепь:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/20aa87fefe6adf3989884422c259a4596d9e48d4.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Дана цепь. Ваша задача сопоставить сопротивления всем резисторам, так чтобы были выполнены следующие требования:</p><ul> <li> Каждому резистору сопоставлено <span class="tex-font-style-underline">неотрицательное целое</span> сопротивление; </li><li> Сопротивление всей цепи равно $$$r$$$; </li><li> Сумма сопротивлений всех резисторов минимально возможная. </li></ul><p>Если в схеме есть $$$n$$$ резисторов, то вам нужно найти список $$$r_1, r_2, \ldots, r_n$$$ ($$$0 \le r_i$$$, $$$r_i$$$ целое число), где $$$r_i$$$ это сопротивление сопоставленное $$$i$$$-у резистору в строке (слева направо), представляющей данную цепь. Если сделать сопоставление, в котором все условия выполнены невозможно, то сообщите об этом.</p><p>Если это сделать возможно, гарантируется, что минимальная сумма сопротивлений всех резисторов не превосходит $$$10^{18}$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 32000$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>Для каждого тестового случая в единственной строке находится целое число $$$r$$$ ($$$1 \le r \le 10^6$$$), пробел а затем строка, которая представляет некоторую цепь. Гарантируется, что эта строка корректна по определениям из условия задачи и действительно представляет некоторую цепь. Количество резисторов (символов равных «<span class="tex-font-style-tt">*</span>») не меньше, чем $$$1$$$ и не больше, чем $$$80000$$$.</p><p>Гарантируется что суммарное количество резисторов по всем тестовым случаям не превосходит $$$320000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите ответ:</p><ul> <li> Если возможно получить сопротивление данной цепи, равное $$$r$$$, выведите «<span class="tex-font-style-tt">REVOLTING</span>» (без кавычек) и затем $$$n$$$ неотрицательных целых чисел $$$r_1, r_2, \ldots, r_n$$$ — сопротивления сопоставленные резисторам. Здесь $$$n$$$ обозначает количество резисторов в цепи.<p> Если существует несколько возможных сопоставлений с минимальной суммой сопротивлений резисторов, вы можете найти любое из них;</p><p> </p></li><li> Если это невозможно выведите единственную строку: «<span class="tex-font-style-tt">LOSS</span>» (без кавычек). </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 * 1 (* S *) 1 (* P (* S *)) </pre></div><div class="output"><div class="title">Выходные данные</div><pre> REVOLTING 5 REVOLTING 1 0 REVOLTING 2 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Эта картинка иллюстрирует третий тестовый случай:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/228fdf51e9ffa6c9dcf58356af80229d8243dba9.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Здесь сумма сопротивлений всех резисторов равна $$$2 + 1 + 1 = 4$$$ и можно показать, что она минимально возможная. Обратите внимание, что существуют другие возможные способы достичь эту минимальную сумму.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:53: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:'8124924a6ef77b1f',t:'MTY5NjY2NTIxOC4xMDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2900"]
1280F
1280
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>Вы межгалактический хирург, и у вас есть инопланетный пациент. Для целей этой задачи мы будем моделировать тело этого пациента, используя прямоугольную сетку размером $$$2 \times (2k + 1)$$$. Инопланетянин имеет $$$4k + 1$$$ различных органов, пронумерованных целыми числами от $$$1$$$ до $$$4k + 1$$$.</p><p>У здоровых инопланетян органы устроены особым образом. Например, вот как будут расположены органы здорового инопланетянина, если смотреть сверху, для $$$k = 4$$$:</p><center> <img class="tex-graphics" height="128px" src="https://espresso.codeforces.com/40236c5ec3cfadb3e0a76c1d5f5e8c2a343a993f.png" style="max-width: 100.0%;max-height: 100.0%;" width="643px"/> </center><p>Здесь <span class="tex-font-style-tt">E</span> обозначает пустое место.</p><p>В общем случае у здорового инопланетянина первая строка содержит органы от $$$1$$$ до $$$2k + 1$$$ (в порядке слева направо) и вторая строка содержит органы от $$$2k + 2$$$ до $$$4k + 1$$$ (в порядке слева направо) и пустое место после этого, в конце второй строки.</p><p>Органы вашего пациента целы, и находятся внутри его тела, но они каким-то образом перемешались! Ваша задача, как межгалактического хирурга, состоит в том, чтобы вернуть все органы свои места. Все органы пришельца должны находиться в его теле в течение всей процедуры. Это означает, что в любой момент времени во время процедуры есть ровно одна ячейка (в сетке), которая пуста. Кроме того, вы можете перемещать органы только одним из следующих способов:</p><ul> <li> Вы можете поменять пустую позицию <span class="tex-font-style-tt">E</span> с любым органом непосредственно слева или справа от нее (если они существуют). Вы делаете это, перемещая рассматриваемый орган в пустое место; </li><li> Вы можете поменять пустую позицию <span class="tex-font-style-tt">E</span> с любым органом непосредственно сверху или снизу от нее (если они существуют). Это можно сделать <span class="tex-font-style-underline">только если</span> пустая позиция в <span class="tex-font-style-underline">самой левой</span> колонке, <span class="tex-font-style-underline">самой правой</span> колонке или <span class="tex-font-style-underline">центральной</span> колонке. Аналогично вы перемещаете рассматриваемый орган в пустое место. </li></ul><p>Вашей задачей является получить последовательность шагов которые вы должны сделать при операции, чтобы вернуть все $$$4k + 1$$$ органов пациента на правильные места. Если это сделать невозможно, вы должны сообщить об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 4$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>Каждый тестовый случай содержит три строки. Первая строка содержит единственное целое число $$$k$$$ ($$$1 \le k \le 15$$$), которое задает размер сетки. Затем следует две строки. Каждая из них содержит $$$2k + 1$$$ целое число или символ <span class="tex-font-style-tt">E</span>. Они описывают первую и вторую строку органов, соответственно. Гарантируется, что все $$$4k + 1$$$ органов присутствуют и также был ровно один символ <span class="tex-font-style-tt">E</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите сначала строку, содержащую:</p><ul> <li> <span class="tex-font-style-tt">SURGERY COMPLETE</span> если возможно вернуть все органы на изначальные места по правилам; </li><li> <span class="tex-font-style-tt">SURGERY FAILED</span> если это невозможно. </li></ul><p>Если было невозможно, то это была единственная строка вывода для этого тестового случая. Если это возможно, выведите строку, описывающую последовательность ходов, чтобы вернуть все органы на изначальные места.</p><p>Строкой ходов (возможно пустой) является строка из символов <span class="tex-font-style-tt">u</span>, <span class="tex-font-style-tt">d</span>, <span class="tex-font-style-tt">l</span> или <span class="tex-font-style-tt">r</span>, обозначающие действия замены пустой позиции с органом непосредственно сверху, снизу, слева или справа, соответсвенно. Выведите последовательность ходов в следующей строке в этом формате.</p><p>Для удобства, вы можете использовать <span class="tex-font-style-bf">сокращения</span> для уменьшения размера вывода. Вы можете использовать большие латинские буквы как сокращения последовательности команд. Например, вы можете использовать <span class="tex-font-style-tt">T</span> для представления строки <span class="tex-font-style-tt">lddrr</span>. Эти сокращения могут использоваться внутри других сокращений! Например, вы можете использовать <span class="tex-font-style-tt">E</span> для того, чтобы обозначить <span class="tex-font-style-tt">TruT</span>, и так далее.</p><p>Вы можете использовать любое количество больших латинских букв (включая ноль) как сокращения. Единственные требования это:</p><ul> <li> Суммарная длина выведенных строк для одного тестового случая не превосходит $$$10^4$$$; </li><li> Не должно быть циклов на сокращениях, которые достижимы из главной последовательности; </li><li> Итоговая последовательность конечна после раскрытия всех замен. Заметьте, что итоговая последовательность (после раскрытия) может быть длиннее чем $$$10^4$$$, единственное ограничение это конечность. </li></ul><p>Например, если <span class="tex-font-style-tt">T = lddrr</span>, <span class="tex-font-style-tt">E = TruT</span> и <span class="tex-font-style-tt">R = rrr</span>, тогда <span class="tex-font-style-tt">TurTlER</span> раскроется в:</p><ul> <li> <span class="tex-font-style-tt">TurTlER</span> </li><li> <span class="tex-font-style-tt"><span class="tex-font-style-bf">lddrr</span>urTlER</span> </li><li> <span class="tex-font-style-tt">lddrrur<span class="tex-font-style-bf">lddrr</span>lER</span> </li><li> <span class="tex-font-style-tt">lddrrurlddrrl<span class="tex-font-style-bf">TruT</span>R</span> </li><li> <span class="tex-font-style-tt">lddrrurlddrrl<span class="tex-font-style-bf">lddrr</span>ruTR</span> </li><li> <span class="tex-font-style-tt">lddrrurlddrrllddrrru<span class="tex-font-style-bf">lddrr</span>R</span> </li><li> <span class="tex-font-style-tt">lddrrurlddrrllddrrrulddrr<span class="tex-font-style-bf">rrr</span></span> </li></ul><p>Для того, чтобы использовать сокращение выведите их по одному в строке как большой латинский символ, затем пробел, затем строка, которую сокращает этот символ. Вы можете выводить сокращения в любом порядке. После этого вы должны вывести строку содержащую слово <span class="tex-font-style-tt">DONE</span>.</p><p><span class="tex-font-style-bf">Замечание:</span> вам нужно вывести <span class="tex-font-style-tt">DONE</span> даже если вы не собираетесь использовать сокращения.</p><p>Ваша последовательность не обязана получиться кратчайшей. Любая подходящая последовательность перемещений (удовлетворяющая всем ограничениям) будет принята.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 1 2 3 5 6 E 7 8 9 10 4 11 12 13 11 34 45 6 22 16 43 38 44 5 4 41 14 7 29 28 19 9 18 42 8 17 33 1 E 15 40 36 31 24 10 2 21 11 32 23 30 27 35 25 13 12 39 37 26 20 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> SURGERY COMPLETE IR R SrS S rr I lldll DONE SURGERY FAILED </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Так три сокращения выглядят в первом тестовом случае:</p><ul> <li> <span class="tex-font-style-tt">R = SrS</span> </li><li> <span class="tex-font-style-tt">S = rr</span> </li><li> <span class="tex-font-style-tt">I = lldll</span> </li></ul><p>Тогда последовательность команд <span class="tex-font-style-tt">IR</span> раскроется в:</p><ul> <li> <span class="tex-font-style-tt">IR</span> </li><li> <span class="tex-font-style-tt"><span class="tex-font-style-bf">lldll</span>R</span> </li><li> <span class="tex-font-style-tt">lldll<span class="tex-font-style-bf">SrS</span></span> </li><li> <span class="tex-font-style-tt">lldll<span class="tex-font-style-bf">rr</span>rS</span> </li><li> <span class="tex-font-style-tt">lldllrrr<span class="tex-font-style-bf">rr</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="8dce2a56c1a600318ca7947c960d8c26"/> <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="e32544b9cb685be4a903dab3307027ab419a190c"/> <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='8dce2a56c1a600318ca7947c960d8c26'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1280%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='8dce2a56c1a600318ca7947c960d8c26'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1280">Codeforces Round 607 (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='8dce2a56c1a600318ca7947c960d8c26'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1280/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='8dce2a56c1a600318ca7947c960d8c26'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="495765"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8dce2a56c1a600318ca7947c960d8c26'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="495765"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72165" title="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10064" resourceName="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" resourceManual="true" src="//codeforces.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/72212" title="Codeforces Round #607 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10080" resourceName="Codeforces Round #607 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/1280">Задачи</a></li> <li><a href="/contest/1280/submit">Отослать</a></li> <li><a href="/contest/1280/my">Мои посылки</a></li> <li><a href="/contest/1280/status">Статус</a></li> <li><a href="/contest/1280/hacks">Взломы</a></li> <li><a href="/contest/1280/room/1">Комната</a></li> <li><a href="/contest/1280/standings">Положение</a></li> <li><a href="/contest/1280/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_64347a126851df463e00628ef80cbf89cb7194cb"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Вы межгалактический хирург, и у вас есть инопланетный пациент. Для целей этой задачи мы будем моделировать тело этого пациента, используя прямоугольную сетку размером $$$2 \times (2k + 1)$$$. Инопланетянин имеет $$$4k + 1$$$ различных органов, пронумерованных целыми числами от $$$1$$$ до $$$4k + 1$$$.</p><p>У здоровых инопланетян органы устроены особым образом. Например, вот как будут расположены органы здорового инопланетянина, если смотреть сверху, для $$$k = 4$$$:</p><center> <img class="tex-graphics" height="128px" src="https://espresso.codeforces.com/40236c5ec3cfadb3e0a76c1d5f5e8c2a343a993f.png" style="max-width: 100.0%;max-height: 100.0%;" width="643px" /> </center><p>Здесь <span class="tex-font-style-tt">E</span> обозначает пустое место.</p><p>В общем случае у здорового инопланетянина первая строка содержит органы от $$$1$$$ до $$$2k + 1$$$ (в порядке слева направо) и вторая строка содержит органы от $$$2k + 2$$$ до $$$4k + 1$$$ (в порядке слева направо) и пустое место после этого, в конце второй строки.</p><p>Органы вашего пациента целы, и находятся внутри его тела, но они каким-то образом перемешались! Ваша задача, как межгалактического хирурга, состоит в том, чтобы вернуть все органы свои места. Все органы пришельца должны находиться в его теле в течение всей процедуры. Это означает, что в любой момент времени во время процедуры есть ровно одна ячейка (в сетке), которая пуста. Кроме того, вы можете перемещать органы только одним из следующих способов:</p><ul> <li> Вы можете поменять пустую позицию <span class="tex-font-style-tt">E</span> с любым органом непосредственно слева или справа от нее (если они существуют). Вы делаете это, перемещая рассматриваемый орган в пустое место; </li><li> Вы можете поменять пустую позицию <span class="tex-font-style-tt">E</span> с любым органом непосредственно сверху или снизу от нее (если они существуют). Это можно сделать <span class="tex-font-style-underline">только если</span> пустая позиция в <span class="tex-font-style-underline">самой левой</span> колонке, <span class="tex-font-style-underline">самой правой</span> колонке или <span class="tex-font-style-underline">центральной</span> колонке. Аналогично вы перемещаете рассматриваемый орган в пустое место. </li></ul><p>Вашей задачей является получить последовательность шагов которые вы должны сделать при операции, чтобы вернуть все $$$4k + 1$$$ органов пациента на правильные места. Если это сделать невозможно, вы должны сообщить об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 4$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>Каждый тестовый случай содержит три строки. Первая строка содержит единственное целое число $$$k$$$ ($$$1 \le k \le 15$$$), которое задает размер сетки. Затем следует две строки. Каждая из них содержит $$$2k + 1$$$ целое число или символ <span class="tex-font-style-tt">E</span>. Они описывают первую и вторую строку органов, соответственно. Гарантируется, что все $$$4k + 1$$$ органов присутствуют и также был ровно один символ <span class="tex-font-style-tt">E</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите сначала строку, содержащую:</p><ul> <li> <span class="tex-font-style-tt">SURGERY COMPLETE</span> если возможно вернуть все органы на изначальные места по правилам; </li><li> <span class="tex-font-style-tt">SURGERY FAILED</span> если это невозможно. </li></ul><p>Если было невозможно, то это была единственная строка вывода для этого тестового случая. Если это возможно, выведите строку, описывающую последовательность ходов, чтобы вернуть все органы на изначальные места.</p><p>Строкой ходов (возможно пустой) является строка из символов <span class="tex-font-style-tt">u</span>, <span class="tex-font-style-tt">d</span>, <span class="tex-font-style-tt">l</span> или <span class="tex-font-style-tt">r</span>, обозначающие действия замены пустой позиции с органом непосредственно сверху, снизу, слева или справа, соответсвенно. Выведите последовательность ходов в следующей строке в этом формате.</p><p>Для удобства, вы можете использовать <span class="tex-font-style-bf">сокращения</span> для уменьшения размера вывода. Вы можете использовать большие латинские буквы как сокращения последовательности команд. Например, вы можете использовать <span class="tex-font-style-tt">T</span> для представления строки <span class="tex-font-style-tt">lddrr</span>. Эти сокращения могут использоваться внутри других сокращений! Например, вы можете использовать <span class="tex-font-style-tt">E</span> для того, чтобы обозначить <span class="tex-font-style-tt">TruT</span>, и так далее.</p><p>Вы можете использовать любое количество больших латинских букв (включая ноль) как сокращения. Единственные требования это:</p><ul> <li> Суммарная длина выведенных строк для одного тестового случая не превосходит $$$10^4$$$; </li><li> Не должно быть циклов на сокращениях, которые достижимы из главной последовательности; </li><li> Итоговая последовательность конечна после раскрытия всех замен. Заметьте, что итоговая последовательность (после раскрытия) может быть длиннее чем $$$10^4$$$, единственное ограничение это конечность. </li></ul><p>Например, если <span class="tex-font-style-tt">T = lddrr</span>, <span class="tex-font-style-tt">E = TruT</span> и <span class="tex-font-style-tt">R = rrr</span>, тогда <span class="tex-font-style-tt">TurTlER</span> раскроется в:</p><ul> <li> <span class="tex-font-style-tt">TurTlER</span> </li><li> <span class="tex-font-style-tt"><span class="tex-font-style-bf">lddrr</span>urTlER</span> </li><li> <span class="tex-font-style-tt">lddrrur<span class="tex-font-style-bf">lddrr</span>lER</span> </li><li> <span class="tex-font-style-tt">lddrrurlddrrl<span class="tex-font-style-bf">TruT</span>R</span> </li><li> <span class="tex-font-style-tt">lddrrurlddrrl<span class="tex-font-style-bf">lddrr</span>ruTR</span> </li><li> <span class="tex-font-style-tt">lddrrurlddrrllddrrru<span class="tex-font-style-bf">lddrr</span>R</span> </li><li> <span class="tex-font-style-tt">lddrrurlddrrllddrrrulddrr<span class="tex-font-style-bf">rrr</span></span> </li></ul><p>Для того, чтобы использовать сокращение выведите их по одному в строке как большой латинский символ, затем пробел, затем строка, которую сокращает этот символ. Вы можете выводить сокращения в любом порядке. После этого вы должны вывести строку содержащую слово <span class="tex-font-style-tt">DONE</span>.</p><p><span class="tex-font-style-bf">Замечание:</span> вам нужно вывести <span class="tex-font-style-tt">DONE</span> даже если вы не собираетесь использовать сокращения.</p><p>Ваша последовательность не обязана получиться кратчайшей. Любая подходящая последовательность перемещений (удовлетворяющая всем ограничениям) будет принята.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 1 2 3 5 6 E 7 8 9 10 4 11 12 13 11 34 45 6 22 16 43 38 44 5 4 41 14 7 29 28 19 9 18 42 8 17 33 1 E 15 40 36 31 24 10 2 21 11 32 23 30 27 35 25 13 12 39 37 26 20 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> SURGERY COMPLETE IR R SrS S rr I lldll DONE SURGERY FAILED </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Так три сокращения выглядят в первом тестовом случае:</p><ul> <li> <span class="tex-font-style-tt">R = SrS</span> </li><li> <span class="tex-font-style-tt">S = rr</span> </li><li> <span class="tex-font-style-tt">I = lldll</span> </li></ul><p>Тогда последовательность команд <span class="tex-font-style-tt">IR</span> раскроется в:</p><ul> <li> <span class="tex-font-style-tt">IR</span> </li><li> <span class="tex-font-style-tt"><span class="tex-font-style-bf">lldll</span>R</span> </li><li> <span class="tex-font-style-tt">lldll<span class="tex-font-style-bf">SrS</span></span> </li><li> <span class="tex-font-style-tt">lldll<span class="tex-font-style-bf">rr</span>rS</span> </li><li> <span class="tex-font-style-tt">lldllrrr<span class="tex-font-style-bf">rr</span></span> </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:53: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:'81249254d8411616',t:'MTY5NjY2NTIxOS40NjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*3400"]
1281A
1281
A
ru
A. Suffix Three
<div class="problem-statement"><div class="header"><div class="title">A. Suffix Three</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Мы открыли новую структуру данных в нашей исследовательской группе — <span class="tex-font-style-bf">suffix three</span>!</p><p>Она очень полезна при обработке естественных языков. Если даны три языка и три суффикса, то suffix three может определить на каком языке написано предложение.</p><p>Это очень просто, 100% точно и не использует никакого продвинутого машинного обучения.</p><p>Давайте же узнаем, как эта структура работает!</p><ul> <li> Если предложение заканчивается на «<span class="tex-font-style-tt">po</span>», язык —- филиппинский; </li><li> Если предложение заканчивается на «<span class="tex-font-style-tt">desu</span>» или «<span class="tex-font-style-tt">masu</span>», язык — японский; </li><li> Если предложение заканчивается на «<span class="tex-font-style-tt">mnida</span>», язык — корейский. </li></ul><p>Зная это вам предлагается реализовать структуру suffix three, которая будет различать филиппинский, японский и корейский языки.</p><p>Подождите, я сказал про три суффикса? Я имел ввиду четыре.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 30$$$), количество наборов входных данных. В следующих строках находятся их описания.</p><p>Каждый набор входных данных состоит из одной строки, обозначающую предложение. Пробелы представлены нижними подчеркиваниями (символом «<span class="tex-font-style-tt">_</span>»). Предложение содержит от $$$1$$$ до $$$1000$$$ символов (включительно) и состоит только из строчных латинских букв и нижних подчеркиваний. Предложение не содержит нижних подчеркиваний в начале и в конце, два последовательных нижних подчеркивания. Гарантируется, что предложение заканчивается одним из четырех суффиксов, описанных в условии задачи.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите строку, содержащую «<span class="tex-font-style-tt">FILIPINO</span>», «<span class="tex-font-style-tt">JAPANESE</span>» или «<span class="tex-font-style-tt">KOREAN</span>» (все буквы большие, без кавычек), если предложение написано на филиппинском, японском и корейском языках, соответственно.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 kamusta_po genki_desu ohayou_gozaimasu annyeong_hashimnida hajime_no_ippo bensamu_no_sentou_houhou_ga_okama_kenpo ang_halaman_doon_ay_sarisari_singkamasu si_roy_mustang_ay_namamasu </pre></div><div class="output"><div class="title">Выходные данные</div><pre> FILIPINO JAPANESE JAPANESE KOREAN FILIPINO FILIPINO JAPANESE JAPANESE </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первое предложение заканчивается на «<span class="tex-font-style-tt">po</span>», поэтому оно написано на филиппинском.</p><p>Второе и третье предложения заканчиваются на «<span class="tex-font-style-tt">desu</span>» и «<span class="tex-font-style-tt">masu</span>» соответственно, поэтому они написаны на японском.</p><p>Четвертое предложение заканчивается на «<span class="tex-font-style-tt">mnida</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="91b46ff54b2621636f4045691466b1f7"/> <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="ec7b9d0d41f1d0f3c3b40a2d06766880163915f7"/> <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='91b46ff54b2621636f4045691466b1f7'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1281%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='91b46ff54b2621636f4045691466b1f7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1281">Codeforces Round 607 (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='91b46ff54b2621636f4045691466b1f7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1281/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='91b46ff54b2621636f4045691466b1f7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="495766"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='91b46ff54b2621636f4045691466b1f7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="495766"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72165" title="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10063" resourceName="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" resourceManual="true" src="//codeforces.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/72212" title="Codeforces Round #607 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10079" resourceName="Codeforces Round #607 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/1281">Задачи</a></li> <li><a href="/contest/1281/submit">Отослать</a></li> <li><a href="/contest/1281/my">Мои посылки</a></li> <li><a href="/contest/1281/status">Статус</a></li> <li><a href="/contest/1281/hacks">Взломы</a></li> <li><a href="/contest/1281/room/1">Комната</a></li> <li><a href="/contest/1281/standings">Положение</a></li> <li><a href="/contest/1281/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d087508195bdbef497851aebea38239e9abb57ce"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Suffix Three</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Мы открыли новую структуру данных в нашей исследовательской группе — <span class="tex-font-style-bf">suffix three</span>!</p><p>Она очень полезна при обработке естественных языков. Если даны три языка и три суффикса, то suffix three может определить на каком языке написано предложение.</p><p>Это очень просто, 100% точно и не использует никакого продвинутого машинного обучения.</p><p>Давайте же узнаем, как эта структура работает!</p><ul> <li> Если предложение заканчивается на «<span class="tex-font-style-tt">po</span>», язык —- филиппинский; </li><li> Если предложение заканчивается на «<span class="tex-font-style-tt">desu</span>» или «<span class="tex-font-style-tt">masu</span>», язык — японский; </li><li> Если предложение заканчивается на «<span class="tex-font-style-tt">mnida</span>», язык — корейский. </li></ul><p>Зная это вам предлагается реализовать структуру suffix three, которая будет различать филиппинский, японский и корейский языки.</p><p>Подождите, я сказал про три суффикса? Я имел ввиду четыре.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 30$$$), количество наборов входных данных. В следующих строках находятся их описания.</p><p>Каждый набор входных данных состоит из одной строки, обозначающую предложение. Пробелы представлены нижними подчеркиваниями (символом «<span class="tex-font-style-tt">_</span>»). Предложение содержит от $$$1$$$ до $$$1000$$$ символов (включительно) и состоит только из строчных латинских букв и нижних подчеркиваний. Предложение не содержит нижних подчеркиваний в начале и в конце, два последовательных нижних подчеркивания. Гарантируется, что предложение заканчивается одним из четырех суффиксов, описанных в условии задачи.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите строку, содержащую «<span class="tex-font-style-tt">FILIPINO</span>», «<span class="tex-font-style-tt">JAPANESE</span>» или «<span class="tex-font-style-tt">KOREAN</span>» (все буквы большие, без кавычек), если предложение написано на филиппинском, японском и корейском языках, соответственно.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 kamusta_po genki_desu ohayou_gozaimasu annyeong_hashimnida hajime_no_ippo bensamu_no_sentou_houhou_ga_okama_kenpo ang_halaman_doon_ay_sarisari_singkamasu si_roy_mustang_ay_namamasu </pre></div><div class="output"><div class="title">Выходные данные</div><pre> FILIPINO JAPANESE JAPANESE KOREAN FILIPINO FILIPINO JAPANESE JAPANESE </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первое предложение заканчивается на «<span class="tex-font-style-tt">po</span>», поэтому оно написано на филиппинском.</p><p>Второе и третье предложения заканчиваются на «<span class="tex-font-style-tt">desu</span>» и «<span class="tex-font-style-tt">masu</span>» соответственно, поэтому они написаны на японском.</p><p>Четвертое предложение заканчивается на «<span class="tex-font-style-tt">mnida</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:53: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:'8124925d5c2275ab',t:'MTY5NjY2NTIyMC45MTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1281B
1281
B
ru
B. Azamon Web Services
<div class="problem-statement"><div class="header"><div class="title">B. Azamon Web Services</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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">Azamon</span> ваш друг Jeff Zebos запустил новую онлайн-кампанию. Однако он не смог привлечь так много посетителей, как планировал. Вам кажется, что самая большая проблема заключается в том, что его сайт не получает высокие места в выдаче поисковых систем. Только если он изменит названия продуктов на такие, которые будут лучше чем у конкурентов, он сможет оказаться на первой строчке в поиске и станет миллионером!</p><p>После некоторого исследования, вы заметили, что в поиске результаты отсортированы лексикографически. Если ваш друг сможет переименовать свои продукты на лексикографически меньшие строки, чем у конкурентов, он будет первым в поиске!</p><p>Чтобы сделать стратегию менее очевидной для конкурентов, вы решили поменять местами не больше одной пары символов в названиях продуктов.</p><p>Пожалуйста, помогите другу улучшить названия своих продуктов, так чтобы они стали лексикографически меньше названия продуктов его конкурентов.</p><p>Вам дана строка $$$s$$$, являющаяся названием продукта компании Azamon и строка $$$c$$$, являющаяся названием продукта компании конкурента. Найдите некоторый способ поменять <span class="tex-font-style-bf">не больше одной</span> пары символов в строке $$$s$$$ (это означает выбрать два различных индекса $$$i$$$ и $$$j$$$ и поменять местами символы $$$s_i$$$ и $$$s_j$$$ в строке), так чтобы новое имя стало лексикографически меньше, чем $$$c$$$. Если это невозможно, определите это.</p><p><span class="tex-font-style-bf">Примечание:</span> Строка $$$a$$$ <span class="tex-font-style-underline">лексикографически меньше</span> чем строка $$$b$$$, тогда и только тогда, когда одно из следующих двух условий выполнено:</p><ul> <li> $$$a$$$ это <span class="tex-font-style-underline">собственный префикс</span> строки $$$b$$$, то есть, $$$a$$$ это <span class="tex-font-style-underline">префикс</span> строки $$$b$$$ и $$$a \neq b$$$; </li><li> Существует целое $$$1 \le i \le \min{(|a|, |b|)}$$$, такое что $$$a_i &lt; b_i$$$ и $$$a_j = b_j$$$ для всех $$$1 \le j &lt; i$$$. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано единственное целое число $$$t$$$ ($$$1 \le t \le 1500$$$), количество наборов входных данных. В следующих строках находятся их описания.</p><p>Каждый набор входных данных содержит две строки $$$s$$$ и $$$c$$$, разделенные пробелом ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). Строки $$$s$$$ и $$$c$$$ состоят из прописных букв латинского алфавита.</p><p>Гарантируется, что сумма $$$|s|$$$ по всем тестовым случаям не превосходит $$$5000$$$ и что сумма $$$|c|$$$ по всем тестовым случаям не превосходит $$$5000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите строку, содержащую ответ. Ответом на набор входных данных является:</p><ul> <li> новое имя, которое может быть получено из старого обменом не более одной пары символов, которое будет лексикографически меньше, чем $$$c$$$. В случае, если существует несколько возможных ответов, вы можете вывести любой из них; </li><li> три знака минус (строка «<span class="tex-font-style-tt">---</span>» без кавычек) если новое имя, удовлетворяющее условию, получить невозможно. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 AZAMON APPLE AZAMON AAAAAAAAAAALIBABA APPLE BANANA </pre></div><div class="output"><div class="title">Выходные данные</div><pre> AMAZON --- APPLE </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно поменять второй и четвертый символы строки и получится строка «<span class="tex-font-style-tt">AMAZON</span>», которая лексикографически меньше чем «<span class="tex-font-style-tt">APPLE</span>».</p><p>Во втором наборе входных данных невозможно улучшить имя продукта так, чтобы удовлетворить все условия.</p><p>В третьем наборе входных данных, можно не делать замены пары символов. Это верно, потому что имя «<span class="tex-font-style-tt">APPLE</span>» лексикографически меньше, чем имя «<span class="tex-font-style-tt">BANANA</span>». Заметьте, что возможны и другие ответы, например «<span class="tex-font-style-tt">APPEL</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="3fbe51f48a987cbc4a40d4e236d19a31"/> <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="ec7b9d0d41f1d0f3c3b40a2d06766880163915f7"/> <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='3fbe51f48a987cbc4a40d4e236d19a31'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1281%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='3fbe51f48a987cbc4a40d4e236d19a31'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1281">Codeforces Round 607 (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='3fbe51f48a987cbc4a40d4e236d19a31'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1281/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='3fbe51f48a987cbc4a40d4e236d19a31'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="495767"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3fbe51f48a987cbc4a40d4e236d19a31'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="495767"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72165" title="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10063" resourceName="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" resourceManual="true" src="//codeforces.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/72212" title="Codeforces Round #607 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10079" resourceName="Codeforces Round #607 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/1281">Задачи</a></li> <li><a href="/contest/1281/submit">Отослать</a></li> <li><a href="/contest/1281/my">Мои посылки</a></li> <li><a href="/contest/1281/status">Статус</a></li> <li><a href="/contest/1281/hacks">Взломы</a></li> <li><a href="/contest/1281/room/1">Комната</a></li> <li><a href="/contest/1281/standings">Положение</a></li> <li><a href="/contest/1281/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_837ceccdb06c3bb40773ce2158d45c128bd51eee"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Azamon Web Services</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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">Azamon</span> ваш друг Jeff Zebos запустил новую онлайн-кампанию. Однако он не смог привлечь так много посетителей, как планировал. Вам кажется, что самая большая проблема заключается в том, что его сайт не получает высокие места в выдаче поисковых систем. Только если он изменит названия продуктов на такие, которые будут лучше чем у конкурентов, он сможет оказаться на первой строчке в поиске и станет миллионером!</p><p>После некоторого исследования, вы заметили, что в поиске результаты отсортированы лексикографически. Если ваш друг сможет переименовать свои продукты на лексикографически меньшие строки, чем у конкурентов, он будет первым в поиске!</p><p>Чтобы сделать стратегию менее очевидной для конкурентов, вы решили поменять местами не больше одной пары символов в названиях продуктов.</p><p>Пожалуйста, помогите другу улучшить названия своих продуктов, так чтобы они стали лексикографически меньше названия продуктов его конкурентов.</p><p>Вам дана строка $$$s$$$, являющаяся названием продукта компании Azamon и строка $$$c$$$, являющаяся названием продукта компании конкурента. Найдите некоторый способ поменять <span class="tex-font-style-bf">не больше одной</span> пары символов в строке $$$s$$$ (это означает выбрать два различных индекса $$$i$$$ и $$$j$$$ и поменять местами символы $$$s_i$$$ и $$$s_j$$$ в строке), так чтобы новое имя стало лексикографически меньше, чем $$$c$$$. Если это невозможно, определите это.</p><p><span class="tex-font-style-bf">Примечание:</span> Строка $$$a$$$ <span class="tex-font-style-underline">лексикографически меньше</span> чем строка $$$b$$$, тогда и только тогда, когда одно из следующих двух условий выполнено:</p><ul> <li> $$$a$$$ это <span class="tex-font-style-underline">собственный префикс</span> строки $$$b$$$, то есть, $$$a$$$ это <span class="tex-font-style-underline">префикс</span> строки $$$b$$$ и $$$a \neq b$$$; </li><li> Существует целое $$$1 \le i \le \min{(|a|, |b|)}$$$, такое что $$$a_i &lt; b_i$$$ и $$$a_j = b_j$$$ для всех $$$1 \le j &lt; i$$$. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано единственное целое число $$$t$$$ ($$$1 \le t \le 1500$$$), количество наборов входных данных. В следующих строках находятся их описания.</p><p>Каждый набор входных данных содержит две строки $$$s$$$ и $$$c$$$, разделенные пробелом ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). Строки $$$s$$$ и $$$c$$$ состоят из прописных букв латинского алфавита.</p><p>Гарантируется, что сумма $$$|s|$$$ по всем тестовым случаям не превосходит $$$5000$$$ и что сумма $$$|c|$$$ по всем тестовым случаям не превосходит $$$5000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите строку, содержащую ответ. Ответом на набор входных данных является:</p><ul> <li> новое имя, которое может быть получено из старого обменом не более одной пары символов, которое будет лексикографически меньше, чем $$$c$$$. В случае, если существует несколько возможных ответов, вы можете вывести любой из них; </li><li> три знака минус (строка «<span class="tex-font-style-tt">---</span>» без кавычек) если новое имя, удовлетворяющее условию, получить невозможно. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 AZAMON APPLE AZAMON AAAAAAAAAAALIBABA APPLE BANANA </pre></div><div class="output"><div class="title">Выходные данные</div><pre> AMAZON --- APPLE </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно поменять второй и четвертый символы строки и получится строка «<span class="tex-font-style-tt">AMAZON</span>», которая лексикографически меньше чем «<span class="tex-font-style-tt">APPLE</span>».</p><p>Во втором наборе входных данных невозможно улучшить имя продукта так, чтобы удовлетворить все условия.</p><p>В третьем наборе входных данных, можно не делать замены пары символов. Это верно, потому что имя «<span class="tex-font-style-tt">APPLE</span>» лексикографически меньше, чем имя «<span class="tex-font-style-tt">BANANA</span>». Заметьте, что возможны и другие ответы, например «<span class="tex-font-style-tt">APPEL</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:53: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:'812492667e941693',t:'MTY5NjY2NTIyMi4yMzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1600"]
1281C
1281
C
ru
C. Вырезание и вставка
<div class="problem-statement"><div class="header"><div class="title">C. Вырезание и вставка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Мы начинаем со строки $$$s$$$, состоящей только из цифр $$$1$$$, $$$2$$$ или $$$3$$$. Будем обозначать длину строки $$$s$$$ как $$$|s|$$$. Для всех $$$i$$$ от $$$1$$$ до $$$|s|$$$ $$$i$$$-й символ строки $$$s$$$ обозначим как $$$s_i$$$.</p><p>Где-то в строке стоит курсор. Позиция курсора $$$\ell$$$ обозначается целым числом из множества $$$\{0, \ldots, |s|\}$$$, и имеет следующее значение: </p><ul> <li> если $$$\ell = 0$$$, тогда курсор расположен перед первым символом строки $$$s$$$. </li><li> если $$$\ell = |s|$$$, тогда курсор расположен после последнего символа строки $$$s$$$. </li><li> если $$$0 &lt; \ell &lt; |s|$$$, тогда курсор расположен между символами $$$s_\ell$$$ и $$$s_{\ell+1}$$$. </li></ul><p>Обозначим за $$$s_\text{left}$$$ строку, находящуюся левее курсора и за $$$s_\text{right}$$$ строку находящуюся правее курсора.</p><p>Также есть строка $$$c$$$, которая называется <span class="tex-font-style-underline">буфером</span>, которая изначально пуста. Всего существует три типа действий:</p><ul> <li> <span class="tex-font-style-bf">Передвижение</span>. Передвинуть курсор на один символ вправо. Это увеличивает $$$\ell$$$ на единицу. </li><li> <span class="tex-font-style-bf">Вырезание</span>. Присвоить $$$c \leftarrow s_\text{right}$$$, затем присвоить $$$s \leftarrow s_\text{left}$$$. </li><li> <span class="tex-font-style-bf">Вставка</span>. Добавить значение $$$c$$$ в конец строки $$$s$$$. Заметьте, что это никак не меняет $$$c$$$. </li></ul><p>Изначально курсор находится в позиции $$$\ell = 0$$$. Затем, исполняется следующая процедура:</p><ol> <li> Применить передвижение один раз. </li><li> Применить вырезание один раз. </li><li> Несколько применить вставку, количество раз равно $$$s_\ell$$$. </li><li> Если $$$\ell = x$$$, остановиться. Иначе, вернуться к шагу 1. </li></ol><p>Вам дана изначальная строка $$$s$$$ и целое число $$$x$$$. Какой будет длина строки $$$s$$$ когда процедура остановится? Так как это число может быть очень большим, выведите его остаток при делении на $$$10^9 + 7$$$. </p><p>Гарантируется, что $$$\ell \le |s|$$$ в любой момент времени.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 1000$$$), количество наборов входных данных. В следующих строках находятся их описания.</p><p>В первой строке каждого набора входных данных записано единственное целое число $$$x$$$ ($$$1 \le x \le 10^6$$$). Во второй строке находится изначальная строка $$$s$$$ ($$$1 \le |s| \le 500$$$). Гарантируется, что $$$s$$$ состоит только из символов «<span class="tex-font-style-tt">1</span>», «<span class="tex-font-style-tt">2</span>», «<span class="tex-font-style-tt">3</span>».</p><p>Гарантируется, что сумма $$$x$$$ по всем тестовым случаям не превосходит $$$10^6$$$. Гарантируется, что во всех тестовых случаях во время процедуры $$$\ell \le |s|$$$ в любой момент времени.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите остаток при делении длины строки после процедуры на $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 231 7 2323 6 333 24 133321333 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 25 1438 1101 686531475 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Давайте проиллюстрируем, что происходит в первом тестовом случае. Изначально у нас $$$s = $$$ <span class="tex-font-style-tt">231</span>. Изначально, $$$\ell = 0$$$ и $$$c = \varepsilon$$$ (пустая строка). Вот как изменяются эти значения в ходе процедуры:</p><ul><p> </p><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 1$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2</span> и $$$c = $$$ <span class="tex-font-style-tt">31</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">2</span> раза:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 1 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 2$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23</span> и $$$c = $$$ <span class="tex-font-style-tt">131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">3</span> раза:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 2 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим$$$\ell = 3$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">231</span> и $$$c = $$$ <span class="tex-font-style-tt">31131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">1</span> раз:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 3 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 4$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2313</span> и $$$c = $$$ <span class="tex-font-style-tt">1131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">3</span> раза:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2313113113111311311131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 4 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 5$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131</span> и $$$c = $$$ <span class="tex-font-style-tt">13113111311311131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">1</span> раз:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2313113113111311311131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 5 = x$$$, поэтому мы останавливаемся. </li></ul><p>В конце процедуры, $$$s$$$ имеет длину $$$25$$$. </p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="e18b69b261c38ce84e565d1b52b26524"/> <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="ec7b9d0d41f1d0f3c3b40a2d06766880163915f7"/> <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='e18b69b261c38ce84e565d1b52b26524'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1281%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='e18b69b261c38ce84e565d1b52b26524'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1281">Codeforces Round 607 (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='e18b69b261c38ce84e565d1b52b26524'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1281/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='e18b69b261c38ce84e565d1b52b26524'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="495768"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e18b69b261c38ce84e565d1b52b26524'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="495768"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72165" title="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10063" resourceName="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" resourceManual="true" src="//codeforces.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/72212" title="Codeforces Round #607 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10079" resourceName="Codeforces Round #607 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/1281">Задачи</a></li> <li><a href="/contest/1281/submit">Отослать</a></li> <li><a href="/contest/1281/my">Мои посылки</a></li> <li><a href="/contest/1281/status">Статус</a></li> <li><a href="/contest/1281/hacks">Взломы</a></li> <li><a href="/contest/1281/room/1">Комната</a></li> <li><a href="/contest/1281/standings">Положение</a></li> <li><a href="/contest/1281/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_dfe827dececad99ec0e5c4407ec8ad639caa5531"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Вырезание и вставка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Мы начинаем со строки $$$s$$$, состоящей только из цифр $$$1$$$, $$$2$$$ или $$$3$$$. Будем обозначать длину строки $$$s$$$ как $$$|s|$$$. Для всех $$$i$$$ от $$$1$$$ до $$$|s|$$$ $$$i$$$-й символ строки $$$s$$$ обозначим как $$$s_i$$$.</p><p>Где-то в строке стоит курсор. Позиция курсора $$$\ell$$$ обозначается целым числом из множества $$$\{0, \ldots, |s|\}$$$, и имеет следующее значение: </p><ul> <li> если $$$\ell = 0$$$, тогда курсор расположен перед первым символом строки $$$s$$$. </li><li> если $$$\ell = |s|$$$, тогда курсор расположен после последнего символа строки $$$s$$$. </li><li> если $$$0 &lt; \ell &lt; |s|$$$, тогда курсор расположен между символами $$$s_\ell$$$ и $$$s_{\ell+1}$$$. </li></ul><p>Обозначим за $$$s_\text{left}$$$ строку, находящуюся левее курсора и за $$$s_\text{right}$$$ строку находящуюся правее курсора.</p><p>Также есть строка $$$c$$$, которая называется <span class="tex-font-style-underline">буфером</span>, которая изначально пуста. Всего существует три типа действий:</p><ul> <li> <span class="tex-font-style-bf">Передвижение</span>. Передвинуть курсор на один символ вправо. Это увеличивает $$$\ell$$$ на единицу. </li><li> <span class="tex-font-style-bf">Вырезание</span>. Присвоить $$$c \leftarrow s_\text{right}$$$, затем присвоить $$$s \leftarrow s_\text{left}$$$. </li><li> <span class="tex-font-style-bf">Вставка</span>. Добавить значение $$$c$$$ в конец строки $$$s$$$. Заметьте, что это никак не меняет $$$c$$$. </li></ul><p>Изначально курсор находится в позиции $$$\ell = 0$$$. Затем, исполняется следующая процедура:</p><ol> <li> Применить передвижение один раз. </li><li> Применить вырезание один раз. </li><li> Несколько применить вставку, количество раз равно $$$s_\ell$$$. </li><li> Если $$$\ell = x$$$, остановиться. Иначе, вернуться к шагу 1. </li></ol><p>Вам дана изначальная строка $$$s$$$ и целое число $$$x$$$. Какой будет длина строки $$$s$$$ когда процедура остановится? Так как это число может быть очень большим, выведите его остаток при делении на $$$10^9 + 7$$$. </p><p>Гарантируется, что $$$\ell \le |s|$$$ в любой момент времени.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 1000$$$), количество наборов входных данных. В следующих строках находятся их описания.</p><p>В первой строке каждого набора входных данных записано единственное целое число $$$x$$$ ($$$1 \le x \le 10^6$$$). Во второй строке находится изначальная строка $$$s$$$ ($$$1 \le |s| \le 500$$$). Гарантируется, что $$$s$$$ состоит только из символов «<span class="tex-font-style-tt">1</span>», «<span class="tex-font-style-tt">2</span>», «<span class="tex-font-style-tt">3</span>».</p><p>Гарантируется, что сумма $$$x$$$ по всем тестовым случаям не превосходит $$$10^6$$$. Гарантируется, что во всех тестовых случаях во время процедуры $$$\ell \le |s|$$$ в любой момент времени.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите остаток при делении длины строки после процедуры на $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 231 7 2323 6 333 24 133321333 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 25 1438 1101 686531475 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Давайте проиллюстрируем, что происходит в первом тестовом случае. Изначально у нас $$$s = $$$ <span class="tex-font-style-tt">231</span>. Изначально, $$$\ell = 0$$$ и $$$c = \varepsilon$$$ (пустая строка). Вот как изменяются эти значения в ходе процедуры:</p><ul><p> </p><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 1$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2</span> и $$$c = $$$ <span class="tex-font-style-tt">31</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">2</span> раза:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 1 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 2$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23</span> и $$$c = $$$ <span class="tex-font-style-tt">131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">3</span> раза:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 2 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим$$$\ell = 3$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">231</span> и $$$c = $$$ <span class="tex-font-style-tt">31131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">1</span> раз:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 3 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 4$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2313</span> и $$$c = $$$ <span class="tex-font-style-tt">1131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">3</span> раза:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2313113113111311311131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 4 \not= x = 5$$$, поэтому мы переходим к 1. <p> </p></li><li> <span class="tex-font-style-underline">Шаг 1</span>, <span class="tex-font-style-it">передвижение:</span> мы получим $$$\ell = 5$$$. </li><li> <span class="tex-font-style-underline">Шаг 2</span>, <span class="tex-font-style-it">вырезание:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">23131</span> и $$$c = $$$ <span class="tex-font-style-tt">13113111311311131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 3</span>, <span class="tex-font-style-it">вставка $$$s_\ell = $$$ <span class="tex-font-style-tt">1</span> раз:</span> мы получим $$$s = $$$ <span class="tex-font-style-tt">2313113113111311311131131</span>. </li><li> <span class="tex-font-style-underline">Шаг 4</span>: $$$\ell = 5 = x$$$, поэтому мы останавливаемся. </li></ul><p>В конце процедуры, $$$s$$$ имеет длину $$$25$$$. </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:53: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:'8124926eba2916bf',t:'MTY5NjY2NTIyMy41MjgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1700"]
1281D
1281
D
ru
D. Beingawesomeism
<div class="problem-statement"><div class="header"><div class="title">D. Beingawesomeism</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы всемогущее существо и создали прямоугольный мир. Ваш мир настолько удобный, что может быть представлен в виде таблицы размером $$$r \times c$$$. Каждая клетка этой таблицы обозначает некоторую страну. Каждая страна принадлежит некоторой религии. Всего существует две религии в этом мире. Одна из религий называется Beingawesomeism, люди этой религии делают добрые поступки, чтобы быть хорошими. Другая религия называется Pushingittoofarism, люди этой религии совершают убийства, чтобы быть плохими.</p><p>На самом деле вы не абсолютно всемогущи. У вас есть только одна сила, которую вы можете применить бесконечное число раз! Ваша сила позволяет вам посылать миссионерские группы. Когда миссионерская группа из определенной страны, назовем ее $$$a$$$, приходит в другую страну $$$b$$$, она меняет религию страны $$$b$$$ на религию страны $$$a$$$.</p><p>Силу можно использовать следующим образом: </p><ul> <li> Вы выбираете горизонтальную полоску $$$1 \times x$$$ или вертикальную полоску $$$x \times 1$$$ внутри таблицы. Вы можете выбирать любое значение $$$x$$$; </li><li> Вы выбираете направление $$$d$$$. Если вы выбрали горизонтальную полоску, вы можете выбрать направления СЕВЕР или ЮГ. Если вы выбрали вертикальную полоску, вы можете выбрать направления ВОСТОК или ЗАПАД; </li><li> Вы выбираете количество шагов $$$s$$$; </li><li> Вы командуете каждой стране находящейся внутри выбранной полоски послать миссионерскую группу, которая пройдет $$$s$$$ шагов в направлении $$$d$$$. На каждом шаге, она посетит и возможно поменяет религию (способом описанным ранее) у всех $$$s$$$ стран на своем пути; </li><li> параметры $$$x$$$, $$$d$$$, $$$s$$$ можно выбирать такими, чтобы никакая миссионерская группа не вышла за пределы таблицы. </li></ul><p>Следующая картинка показывает один возможный способ использования силы. Здесь символ <span class="tex-font-style-tt">A</span> обозначает страну с религией Beingawesomeism и символ <span class="tex-font-style-tt">P</span> обозначает страну с религией Pushingittoofarism. Здесь мы выбрали горизонтальную полоску $$$1 \times 4$$$, направление СЕВЕР и количество шагов $$$s = 2$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/5417185338bfaae1779d2924b2c740f9987d6dc2.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Вы существо, которое верит в свободную волю каждого человека. Однако, вы хотите немедленно приостановить убийства. Таким образом вы решили использовать силу и попробовать сделать Beingawesomeism религией всех стран.</p><p>Какое минимальное количество применений силы требуется, чтобы сделать религией каждой страны Beingawesomeism?</p><p>Если это сделать невозможно, вы должны признать свой провал и сообщить об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>Первая строка каждого тестового случая содержит два целых числа $$$r$$$ и $$$c$$$, обозначающие размеры таблицы ($$$1 \le r, c \le 60$$$). Следующие $$$r$$$ строк содержат по $$$c$$$ символов, описывающих религии стран. $$$j$$$-й символ в $$$i$$$-й строке описывает религию страны в строке $$$i$$$ и столбце $$$j$$$. При этом:</p><ul> <li> символ «<span class="tex-font-style-tt">A</span>» означает, что религия Beingawesomeism; </li><li> символ «<span class="tex-font-style-tt">P</span>» означает, что религия Pushingittoofarism. </li></ul><p>Гарантируется, что все символы таблицы это «<span class="tex-font-style-tt">A</span>» или «<span class="tex-font-style-tt">P</span>». Гарантируется, что сумма $$$r \cdot c$$$ по всем тестовым случаям не превосходит $$$3 \cdot 10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите единственную строку, содержащую минимальное возможное количество использований силы нужное, чтобы сделать Beingawesomeism религией во всех странах. Если сделать Beingawesomeism религией во всех странах невозможно, выведите строку «<span class="tex-font-style-tt">MORTAL</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 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 MORTAL 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае можно добиться требуемого за два применения силы.</p><p>Первое использование:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8c0cf3491480a81d4f2affdc3a9cecd5754d45dd.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Второе использование:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/547386a217ca0c1da5e00b77f04b72c07c40b38d.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором тестовом случае можно добиться требуемого за одно применение силы.</p><p>В третьем тестовом случае невозможно сделать религией всех стран Beingawesomeism, поэтому ответ «<span class="tex-font-style-tt">MORTAL</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="68ba37c0466542185f1c554b21160c73"/> <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="ec7b9d0d41f1d0f3c3b40a2d06766880163915f7"/> <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='68ba37c0466542185f1c554b21160c73'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1281%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='68ba37c0466542185f1c554b21160c73'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1281">Codeforces Round 607 (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='68ba37c0466542185f1c554b21160c73'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1281/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='68ba37c0466542185f1c554b21160c73'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="495769"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='68ba37c0466542185f1c554b21160c73'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="495769"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72165" title="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10063" resourceName="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" resourceManual="true" src="//codeforces.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/72212" title="Codeforces Round #607 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10079" resourceName="Codeforces Round #607 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/1281">Задачи</a></li> <li><a href="/contest/1281/submit">Отослать</a></li> <li><a href="/contest/1281/my">Мои посылки</a></li> <li><a href="/contest/1281/status">Статус</a></li> <li><a href="/contest/1281/hacks">Взломы</a></li> <li><a href="/contest/1281/room/1">Комната</a></li> <li><a href="/contest/1281/standings">Положение</a></li> <li><a href="/contest/1281/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d23540f17fcbfe13fb37f83bd6d2f44ff03ce886"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Beingawesomeism</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы всемогущее существо и создали прямоугольный мир. Ваш мир настолько удобный, что может быть представлен в виде таблицы размером $$$r \times c$$$. Каждая клетка этой таблицы обозначает некоторую страну. Каждая страна принадлежит некоторой религии. Всего существует две религии в этом мире. Одна из религий называется Beingawesomeism, люди этой религии делают добрые поступки, чтобы быть хорошими. Другая религия называется Pushingittoofarism, люди этой религии совершают убийства, чтобы быть плохими.</p><p>На самом деле вы не абсолютно всемогущи. У вас есть только одна сила, которую вы можете применить бесконечное число раз! Ваша сила позволяет вам посылать миссионерские группы. Когда миссионерская группа из определенной страны, назовем ее $$$a$$$, приходит в другую страну $$$b$$$, она меняет религию страны $$$b$$$ на религию страны $$$a$$$.</p><p>Силу можно использовать следующим образом: </p><ul> <li> Вы выбираете горизонтальную полоску $$$1 \times x$$$ или вертикальную полоску $$$x \times 1$$$ внутри таблицы. Вы можете выбирать любое значение $$$x$$$; </li><li> Вы выбираете направление $$$d$$$. Если вы выбрали горизонтальную полоску, вы можете выбрать направления СЕВЕР или ЮГ. Если вы выбрали вертикальную полоску, вы можете выбрать направления ВОСТОК или ЗАПАД; </li><li> Вы выбираете количество шагов $$$s$$$; </li><li> Вы командуете каждой стране находящейся внутри выбранной полоски послать миссионерскую группу, которая пройдет $$$s$$$ шагов в направлении $$$d$$$. На каждом шаге, она посетит и возможно поменяет религию (способом описанным ранее) у всех $$$s$$$ стран на своем пути; </li><li> параметры $$$x$$$, $$$d$$$, $$$s$$$ можно выбирать такими, чтобы никакая миссионерская группа не вышла за пределы таблицы. </li></ul><p>Следующая картинка показывает один возможный способ использования силы. Здесь символ <span class="tex-font-style-tt">A</span> обозначает страну с религией Beingawesomeism и символ <span class="tex-font-style-tt">P</span> обозначает страну с религией Pushingittoofarism. Здесь мы выбрали горизонтальную полоску $$$1 \times 4$$$, направление СЕВЕР и количество шагов $$$s = 2$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/5417185338bfaae1779d2924b2c740f9987d6dc2.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Вы существо, которое верит в свободную волю каждого человека. Однако, вы хотите немедленно приостановить убийства. Таким образом вы решили использовать силу и попробовать сделать Beingawesomeism религией всех стран.</p><p>Какое минимальное количество применений силы требуется, чтобы сделать религией каждой страны Beingawesomeism?</p><p>Если это сделать невозможно, вы должны признать свой провал и сообщить об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>Первая строка каждого тестового случая содержит два целых числа $$$r$$$ и $$$c$$$, обозначающие размеры таблицы ($$$1 \le r, c \le 60$$$). Следующие $$$r$$$ строк содержат по $$$c$$$ символов, описывающих религии стран. $$$j$$$-й символ в $$$i$$$-й строке описывает религию страны в строке $$$i$$$ и столбце $$$j$$$. При этом:</p><ul> <li> символ «<span class="tex-font-style-tt">A</span>» означает, что религия Beingawesomeism; </li><li> символ «<span class="tex-font-style-tt">P</span>» означает, что религия Pushingittoofarism. </li></ul><p>Гарантируется, что все символы таблицы это «<span class="tex-font-style-tt">A</span>» или «<span class="tex-font-style-tt">P</span>». Гарантируется, что сумма $$$r \cdot c$$$ по всем тестовым случаям не превосходит $$$3 \cdot 10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите единственную строку, содержащую минимальное возможное количество использований силы нужное, чтобы сделать Beingawesomeism религией во всех странах. Если сделать Beingawesomeism религией во всех странах невозможно, выведите строку «<span class="tex-font-style-tt">MORTAL</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 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 MORTAL 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае можно добиться требуемого за два применения силы.</p><p>Первое использование:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8c0cf3491480a81d4f2affdc3a9cecd5754d45dd.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Второе использование:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/547386a217ca0c1da5e00b77f04b72c07c40b38d.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором тестовом случае можно добиться требуемого за одно применение силы.</p><p>В третьем тестовом случае невозможно сделать религией всех стран Beingawesomeism, поэтому ответ «<span class="tex-font-style-tt">MORTAL</span>».</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:53: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:'81249276bea19d37',t:'MTY5NjY2NTIyNC44MDYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1800"]
1281E
1281
E
ru
E. Jeremy Bearimy
<div class="problem-statement"><div class="header"><div class="title">E. Jeremy Bearimy</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Добро пожаловать! Все хорошо.</p><p>Вы прибыли в Среднее место, место между Хорошим местом и Плохим местом. Вам поручено выполнить два задания, одно сделает всех людей счастливыми, другое будет мучить их вечно.</p><p>У вас есть список $$$k$$$ пар людей, которые прибыли в новый район. Вам нужно назначить каждому из $$$2k$$$ людей свой из $$$2k$$$ домов. Каждый человек будет владельцем ровно одного дома и каждый дом будет иметь ровно одного владельца.</p><p>Конечно, в этом районе можно перемещаться между домами. Всего есть $$$2k - 1$$$ дорога, каждая из них соединяет два дома. Требуется некоторое время, чтобы проехать по дороге. Эти времена известны для каждой дороги. Район спроектирован таким образом, что между любыми двумя домами существует ровно один путь по дорогам от одного дома до другого, не проходящий по одной и той же дороге дважды. Другими словами, граф, в котором вершины это дома, а ребра это дороги это дерево.</p><p>Люди в каждой из $$$k$$$ пар людей хорошо дружат и любят ходить в гости. Мы пронумеруем пары людей от $$$1$$$ до $$$k$$$. Обозначим за $$$f(i)$$$ время, которое требуется $$$i$$$-й паре людей, чтобы проехать между домами друг друга.</p><p>Как уже было сказано ранее, вы должны сопоставить каждому из $$$2k$$$ людей один из $$$2k$$$ домов. У вас есть две миссии, одна назначена из Хорошего места, другая назначена из Плохого места. Эти миссии заключаются в следующем:</p><ul> <li> Первая миссия, из Хорошего места, заключается в том, чтобы сопоставить людям дома, так чтобы сумма $$$f(i)$$$ по всем парам $$$i$$$ была минимальна. Давайте обозначим эту минимальную возможную сумму за $$$G$$$. Это дает нам уверенность, что все пары друзей могут легко и эффективно посещать друг друга; </li><li> Вторая миссия, из Плохого места, заключается в том, чтобы сопоставить людям дома, так чтобы сумма $$$f(i)$$$ по всем парам $$$i$$$ была максимальна. Давайте обозначим эту максимальную возможную сумму за $$$B$$$. Это дает нам уверенность, что все пары друзей могут только трудно и неэффективно посещать друг друга; </li></ul><p>Чему равны значения $$$G$$$ и $$$B$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 500$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>Первая строка каждого тестового случая содержит единственное целое число $$$k$$$, обозначающая количество пар людей ($$$1 \le k \le 10^5$$$). В следующих $$$2k - 1$$$ строках находится описание дорог; в $$$i$$$-й строке находится три целых числа $$$a_i, b_i, t_i$$$, которые обозначают, что $$$i$$$-я дорога соединяет дома $$$a_i$$$ и $$$b_i$$$ и требует $$$t_i$$$ единиц времени, чтобы проехать по ней ($$$1 \le a_i, b_i \le 2k$$$, $$$a_i \neq b_i$$$, $$$1 \le t_i \le 10^6$$$). Гарантируется, что данные дороги образуют структуру дерева.</p><p>Гарантируется, что сумма всех $$$k$$$ по всем тестовым случаям не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите два целых числа $$$G$$$ и $$$B$$$, разделенные пробелом.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 1 2 3 3 2 4 2 4 3 4 5 6 5 6 5 2 1 2 1 1 3 2 1 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 33 6 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого тестового случая, мы можем получить минимальную сумму равную $$$G = 15$$$. Один из способов достичь такую сумму это следующее назначение домов:</p><ul> <li> Первой паре людей назначим дома $$$5$$$ и $$$6$$$, что даст нам $$$f(1) = 5$$$; </li><li> Второй паре людей назначим дома $$$1$$$ и $$$4$$$, что даст нам $$$f(2) = 6$$$; </li><li> Третьей паре людей назначим дома $$$3$$$ и $$$2$$$, что даст нам $$$f(3) = 4$$$. </li></ul><p>Обратите внимание, что тогда сумма всех $$$f(i)$$$ это $$$5 + 6 + 4 = 15$$$. </p><p>Также мы можем получить максимальную сумму равной $$$B = 33$$$. Один из способов достичь такую сумму это следующее назначение домов:</p><ul> <li> Первой паре людей назначим дома $$$1$$$ и $$$4$$$, что даст нам $$$f(1) = 6$$$; </li><li> Второй паре людей назначим дома $$$6$$$ и $$$2$$$, что даст нам $$$f(2) = 14$$$; </li><li> Третьей паре людей назначим дома $$$3$$$ и $$$5$$$, что даст нам $$$f(3) = 13$$$. </li></ul><p>Обратите внимание, что тогда сумма всех $$$f(i)$$$ это $$$6 + 14 + 13 = 33$$$. </p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="293eb7e4d213d3230bc1b69ba58b1efb"/> <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="ec7b9d0d41f1d0f3c3b40a2d06766880163915f7"/> <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='293eb7e4d213d3230bc1b69ba58b1efb'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1281%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='293eb7e4d213d3230bc1b69ba58b1efb'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1281">Codeforces Round 607 (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='293eb7e4d213d3230bc1b69ba58b1efb'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1281/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='293eb7e4d213d3230bc1b69ba58b1efb'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="495770"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='293eb7e4d213d3230bc1b69ba58b1efb'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="495770"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72165" title="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10063" resourceName="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" resourceManual="true" src="//codeforces.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/72212" title="Codeforces Round #607 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10079" resourceName="Codeforces Round #607 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/1281">Задачи</a></li> <li><a href="/contest/1281/submit">Отослать</a></li> <li><a href="/contest/1281/my">Мои посылки</a></li> <li><a href="/contest/1281/status">Статус</a></li> <li><a href="/contest/1281/hacks">Взломы</a></li> <li><a href="/contest/1281/room/1">Комната</a></li> <li><a href="/contest/1281/standings">Положение</a></li> <li><a href="/contest/1281/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9e94f5d390dd1fa726e54e8874513cb7384b8823"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Jeremy Bearimy</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Добро пожаловать! Все хорошо.</p><p>Вы прибыли в Среднее место, место между Хорошим местом и Плохим местом. Вам поручено выполнить два задания, одно сделает всех людей счастливыми, другое будет мучить их вечно.</p><p>У вас есть список $$$k$$$ пар людей, которые прибыли в новый район. Вам нужно назначить каждому из $$$2k$$$ людей свой из $$$2k$$$ домов. Каждый человек будет владельцем ровно одного дома и каждый дом будет иметь ровно одного владельца.</p><p>Конечно, в этом районе можно перемещаться между домами. Всего есть $$$2k - 1$$$ дорога, каждая из них соединяет два дома. Требуется некоторое время, чтобы проехать по дороге. Эти времена известны для каждой дороги. Район спроектирован таким образом, что между любыми двумя домами существует ровно один путь по дорогам от одного дома до другого, не проходящий по одной и той же дороге дважды. Другими словами, граф, в котором вершины это дома, а ребра это дороги это дерево.</p><p>Люди в каждой из $$$k$$$ пар людей хорошо дружат и любят ходить в гости. Мы пронумеруем пары людей от $$$1$$$ до $$$k$$$. Обозначим за $$$f(i)$$$ время, которое требуется $$$i$$$-й паре людей, чтобы проехать между домами друг друга.</p><p>Как уже было сказано ранее, вы должны сопоставить каждому из $$$2k$$$ людей один из $$$2k$$$ домов. У вас есть две миссии, одна назначена из Хорошего места, другая назначена из Плохого места. Эти миссии заключаются в следующем:</p><ul> <li> Первая миссия, из Хорошего места, заключается в том, чтобы сопоставить людям дома, так чтобы сумма $$$f(i)$$$ по всем парам $$$i$$$ была минимальна. Давайте обозначим эту минимальную возможную сумму за $$$G$$$. Это дает нам уверенность, что все пары друзей могут легко и эффективно посещать друг друга; </li><li> Вторая миссия, из Плохого места, заключается в том, чтобы сопоставить людям дома, так чтобы сумма $$$f(i)$$$ по всем парам $$$i$$$ была максимальна. Давайте обозначим эту максимальную возможную сумму за $$$B$$$. Это дает нам уверенность, что все пары друзей могут только трудно и неэффективно посещать друг друга; </li></ul><p>Чему равны значения $$$G$$$ и $$$B$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 500$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>Первая строка каждого тестового случая содержит единственное целое число $$$k$$$, обозначающая количество пар людей ($$$1 \le k \le 10^5$$$). В следующих $$$2k - 1$$$ строках находится описание дорог; в $$$i$$$-й строке находится три целых числа $$$a_i, b_i, t_i$$$, которые обозначают, что $$$i$$$-я дорога соединяет дома $$$a_i$$$ и $$$b_i$$$ и требует $$$t_i$$$ единиц времени, чтобы проехать по ней ($$$1 \le a_i, b_i \le 2k$$$, $$$a_i \neq b_i$$$, $$$1 \le t_i \le 10^6$$$). Гарантируется, что данные дороги образуют структуру дерева.</p><p>Гарантируется, что сумма всех $$$k$$$ по всем тестовым случаям не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите два целых числа $$$G$$$ и $$$B$$$, разделенные пробелом.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 1 2 3 3 2 4 2 4 3 4 5 6 5 6 5 2 1 2 1 1 3 2 1 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 33 6 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого тестового случая, мы можем получить минимальную сумму равную $$$G = 15$$$. Один из способов достичь такую сумму это следующее назначение домов:</p><ul> <li> Первой паре людей назначим дома $$$5$$$ и $$$6$$$, что даст нам $$$f(1) = 5$$$; </li><li> Второй паре людей назначим дома $$$1$$$ и $$$4$$$, что даст нам $$$f(2) = 6$$$; </li><li> Третьей паре людей назначим дома $$$3$$$ и $$$2$$$, что даст нам $$$f(3) = 4$$$. </li></ul><p>Обратите внимание, что тогда сумма всех $$$f(i)$$$ это $$$5 + 6 + 4 = 15$$$. </p><p>Также мы можем получить максимальную сумму равной $$$B = 33$$$. Один из способов достичь такую сумму это следующее назначение домов:</p><ul> <li> Первой паре людей назначим дома $$$1$$$ и $$$4$$$, что даст нам $$$f(1) = 6$$$; </li><li> Второй паре людей назначим дома $$$6$$$ и $$$2$$$, что даст нам $$$f(2) = 14$$$; </li><li> Третьей паре людей назначим дома $$$3$$$ и $$$5$$$, что даст нам $$$f(3) = 13$$$. </li></ul><p>Обратите внимание, что тогда сумма всех $$$f(i)$$$ это $$$6 + 14 + 13 = 33$$$. </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:53: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:'8124927ebdee3aa7',t:'MTY5NjY2NTIyNi4wODkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*2000"]
1281F
1281
F
ru
F. Мисс Punyverse
<div class="problem-statement"><div class="header"><div class="title">F. Мисс Punyverse</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дуб имеет $$$n$$$ гнезд, пронумерованных целыми числами от $$$1$$$ до $$$n$$$. Гнездо $$$i$$$ это дом для $$$b_i$$$ пчел и $$$w_i$$$ ос.</p><p>Некоторые гнезда соединены ветками. Мы называем два гнезда <span class="tex-font-style-underline">соседними</span> если существует ветка, соединяющая их. <span class="tex-font-style-underline">Простой путь</span> из гнезда $$$x$$$ в $$$y$$$ задается последовательностью $$$s_0, \ldots, s_p$$$ различных гнезд, где $$$p$$$ это неотрицательное целое число и $$$s_0 = x$$$, $$$s_p = y$$$ и $$$s_{i-1}$$$ и $$$s_{i}$$$ соседние для всех $$$i = 1, \ldots, p$$$. Ветки дуба расположены так, что для любой пары гнезд $$$x$$$ и $$$y$$$ существует единственный простой путь из $$$x$$$ в $$$y$$$. По причине этого и биологи и программисты согласны, что дуб, по факту, является деревом.</p><p><span class="tex-font-style-underline">Деревня</span> это <span class="tex-font-style-underline">непустое</span> множество $$$V$$$ гнезд, такое что для всех $$$x$$$ и $$$y$$$ из $$$V$$$, существует простой путь из $$$x$$$ в $$$y$$$, все гнезда вдоль которого также лежат в $$$V$$$.</p><p>Множество деревень $$$\cal P$$$ называется <span class="tex-font-style-underline">разбиением</span> если каждое из $$$n$$$ гнезд содержится в ровно одной деревне из $$$\cal P$$$. Другими словами, никакие две деревни из $$$\cal P$$$ не содержат одно и то же гнездо и в объединении дают все $$$n$$$ гнезд.</p><p>На дубе проводится ежегодный конкурс красоты мисс Punyverse. Всего два участника участвуют в этом году, это некрасивая оса и красивая пчела. Победитель конкурса красоты определяется голосованием, систему которого мы сейчас опишем. Пусть $$$\mathcal{P}$$$ это разбиение гнезд на $$$m$$$ деревень $$$V_1, \ldots, V_m$$$. Проводится локальные выборы в каждой деревне. Каждое насекомое в деревне голосует за свое любимое насекомое. Если в деревне окажется, что <span class="tex-font-style-bf">строго</span> больше голосов отдано за некрасивую осу чем за красивую пчелу, тогда некрасивая оса объявляется <span class="tex-font-style-it">победителем</span> в этой деревне. Иначе, красивая пчела <span class="tex-font-style-it">побеждает</span>.</p><p>Известно, что пчелы всегда голосуют за пчел, то есть проголосуют за красивую пчелу в этом году и осы всегда голосуют за ос, то есть проголосуют за некрасивую осу в этом году. Все насекомые в улье участвуют в голосовании.</p><p>Мэр Waspacito, а также его заместитель Alexwasp, хотят, чтобы некрасивая оса победила. Они имеют влияние и могут выбрать разбиение дуба на ровно $$$m$$$ деревень. Если они выберут разбиение оптимально, определите максимальное количество деревень, в которых победит некрасивая оса.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 100$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>В первой строке каждого тестового случая находится два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le m \le n \le 3000$$$). Во второй строке находится $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \le b_i \le 10^9$$$). В третьей строке находится $$$n$$$ целых чисел $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \le w_i \le 10^9$$$). В следующих $$$n - 1$$$ находятся описания соседних пар гнезд, $$$i$$$-я из них содержит два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \neq y_i$$$), обозначающих номера гнезд, соединенных веткой. Гарантируется, что эти пары задают дерево.</p><p>Гарантируется, что сумма $$$n$$$ по всем тестовым случаям не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите целое число, равное максимальному количеству деревень, в которых победит некрасивая оса по всем разбиениям дуба на $$$m$$$ деревень.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 3 10 160 70 50 70 111 111 0 1 2 2 3 3 4 2 1 143 420 214 349 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, нужно разделить $$$n = 4$$$ гнезд на $$$m = 3$$$ деревень. Мы можем так разделить, что некрасивая оса победит в $$$2$$$ деревнях, например с помощью такого разбиения: $$$\{\{1, 2\}, \{3\}, \{4\}\}$$$. В этом разбиении:</p><ul> <li> Некрасивая оса побеждает в деревне $$$\{1, 2\}$$$, получив $$$181$$$ голосов тогда как красивая пчела получила $$$170$$$ голосов; </li><li> Некрасивая оса также побеждает в деревне $$$\{3\}$$$, получив $$$111$$$ голосов тогда как красивая пчела получила $$$70$$$ голосов; </li><li> Некрасивая оса проиграет в деревне $$$\{4\}$$$, получив $$$0$$$ голосов тогда как красивая пчела получила $$$50$$$. </li></ul><p>Таким образом некрасивая оса победила в $$$2$$$ деревнях и можно показать, что это максимально возможное число.</p><p>Во втором тесте мы должны разделить $$$n = 2$$$ гнезд на $$$m = 1$$$ деревень. Есть только один способ это сделать: $$$\{\{1, 2\}\}$$$. В этом разбиении некрасивая оса получит $$$563$$$ голосов и красивая пчела также получит $$$563$$$ голосов. Некрасивая оса побеждает, если получает строго больше голосов. Поэтому некрасивая оса не выиграет ни в какой деревне.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="811b4644fe7c208a73d514ab9c3ceaee"/> <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="ec7b9d0d41f1d0f3c3b40a2d06766880163915f7"/> <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='811b4644fe7c208a73d514ab9c3ceaee'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1281%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='811b4644fe7c208a73d514ab9c3ceaee'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1281">Codeforces Round 607 (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='811b4644fe7c208a73d514ab9c3ceaee'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1281/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='811b4644fe7c208a73d514ab9c3ceaee'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="495771"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='811b4644fe7c208a73d514ab9c3ceaee'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="495771"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72165" title="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10063" resourceName="Codeforces Round #607 (Div.1, Div.2) based on ICPC Manila 2019" resourceManual="true" src="//codeforces.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/72212" title="Codeforces Round #607 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10079" resourceName="Codeforces Round #607 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/1281">Задачи</a></li> <li><a href="/contest/1281/submit">Отослать</a></li> <li><a href="/contest/1281/my">Мои посылки</a></li> <li><a href="/contest/1281/status">Статус</a></li> <li><a href="/contest/1281/hacks">Взломы</a></li> <li><a href="/contest/1281/room/1">Комната</a></li> <li><a href="/contest/1281/standings">Положение</a></li> <li><a href="/contest/1281/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f88cc26d88754277988afd3bd26ec610c99785cf"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Мисс Punyverse</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дуб имеет $$$n$$$ гнезд, пронумерованных целыми числами от $$$1$$$ до $$$n$$$. Гнездо $$$i$$$ это дом для $$$b_i$$$ пчел и $$$w_i$$$ ос.</p><p>Некоторые гнезда соединены ветками. Мы называем два гнезда <span class="tex-font-style-underline">соседними</span> если существует ветка, соединяющая их. <span class="tex-font-style-underline">Простой путь</span> из гнезда $$$x$$$ в $$$y$$$ задается последовательностью $$$s_0, \ldots, s_p$$$ различных гнезд, где $$$p$$$ это неотрицательное целое число и $$$s_0 = x$$$, $$$s_p = y$$$ и $$$s_{i-1}$$$ и $$$s_{i}$$$ соседние для всех $$$i = 1, \ldots, p$$$. Ветки дуба расположены так, что для любой пары гнезд $$$x$$$ и $$$y$$$ существует единственный простой путь из $$$x$$$ в $$$y$$$. По причине этого и биологи и программисты согласны, что дуб, по факту, является деревом.</p><p><span class="tex-font-style-underline">Деревня</span> это <span class="tex-font-style-underline">непустое</span> множество $$$V$$$ гнезд, такое что для всех $$$x$$$ и $$$y$$$ из $$$V$$$, существует простой путь из $$$x$$$ в $$$y$$$, все гнезда вдоль которого также лежат в $$$V$$$.</p><p>Множество деревень $$$\cal P$$$ называется <span class="tex-font-style-underline">разбиением</span> если каждое из $$$n$$$ гнезд содержится в ровно одной деревне из $$$\cal P$$$. Другими словами, никакие две деревни из $$$\cal P$$$ не содержат одно и то же гнездо и в объединении дают все $$$n$$$ гнезд.</p><p>На дубе проводится ежегодный конкурс красоты мисс Punyverse. Всего два участника участвуют в этом году, это некрасивая оса и красивая пчела. Победитель конкурса красоты определяется голосованием, систему которого мы сейчас опишем. Пусть $$$\mathcal{P}$$$ это разбиение гнезд на $$$m$$$ деревень $$$V_1, \ldots, V_m$$$. Проводится локальные выборы в каждой деревне. Каждое насекомое в деревне голосует за свое любимое насекомое. Если в деревне окажется, что <span class="tex-font-style-bf">строго</span> больше голосов отдано за некрасивую осу чем за красивую пчелу, тогда некрасивая оса объявляется <span class="tex-font-style-it">победителем</span> в этой деревне. Иначе, красивая пчела <span class="tex-font-style-it">побеждает</span>.</p><p>Известно, что пчелы всегда голосуют за пчел, то есть проголосуют за красивую пчелу в этом году и осы всегда голосуют за ос, то есть проголосуют за некрасивую осу в этом году. Все насекомые в улье участвуют в голосовании.</p><p>Мэр Waspacito, а также его заместитель Alexwasp, хотят, чтобы некрасивая оса победила. Они имеют влияние и могут выбрать разбиение дуба на ровно $$$m$$$ деревень. Если они выберут разбиение оптимально, определите максимальное количество деревень, в которых победит некрасивая оса.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 100$$$), количество тестовых случаев. В следующих строках находится описание тестовых случаев.</p><p>В первой строке каждого тестового случая находится два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le m \le n \le 3000$$$). Во второй строке находится $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \le b_i \le 10^9$$$). В третьей строке находится $$$n$$$ целых чисел $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \le w_i \le 10^9$$$). В следующих $$$n - 1$$$ находятся описания соседних пар гнезд, $$$i$$$-я из них содержит два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \neq y_i$$$), обозначающих номера гнезд, соединенных веткой. Гарантируется, что эти пары задают дерево.</p><p>Гарантируется, что сумма $$$n$$$ по всем тестовым случаям не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите целое число, равное максимальному количеству деревень, в которых победит некрасивая оса по всем разбиениям дуба на $$$m$$$ деревень.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 3 10 160 70 50 70 111 111 0 1 2 2 3 3 4 2 1 143 420 214 349 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, нужно разделить $$$n = 4$$$ гнезд на $$$m = 3$$$ деревень. Мы можем так разделить, что некрасивая оса победит в $$$2$$$ деревнях, например с помощью такого разбиения: $$$\{\{1, 2\}, \{3\}, \{4\}\}$$$. В этом разбиении:</p><ul> <li> Некрасивая оса побеждает в деревне $$$\{1, 2\}$$$, получив $$$181$$$ голосов тогда как красивая пчела получила $$$170$$$ голосов; </li><li> Некрасивая оса также побеждает в деревне $$$\{3\}$$$, получив $$$111$$$ голосов тогда как красивая пчела получила $$$70$$$ голосов; </li><li> Некрасивая оса проиграет в деревне $$$\{4\}$$$, получив $$$0$$$ голосов тогда как красивая пчела получила $$$50$$$. </li></ul><p>Таким образом некрасивая оса победила в $$$2$$$ деревнях и можно показать, что это максимально возможное число.</p><p>Во втором тесте мы должны разделить $$$n = 2$$$ гнезд на $$$m = 1$$$ деревень. Есть только один способ это сделать: $$$\{\{1, 2\}\}$$$. В этом разбиении некрасивая оса получит $$$563$$$ голосов и красивая пчела также получит $$$563$$$ голосов. Некрасивая оса побеждает, если получает строго больше голосов. Поэтому некрасивая оса не выиграет ни в какой деревне.</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:53: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:'81249286d97a75ab',t:'MTY5NjY2NTIyNy4zOTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*2500"]
1282A
1282
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>Поликарп живет на координатной оси $$$Ox$$$ и путешествует из точки $$$x=a$$$ в $$$x=b$$$. Он двигается равномерно прямолинейно со скоростью одна единица расстояния в минуту.</p><p>На оси $$$Ox$$$ в точке $$$x=c$$$ находится базовая станция оператора сотовой связи. Известно, что радиус её покрытия составляет $$$r$$$. Таким образом, если абонент находится на расстоянии меньшем или равном $$$r$$$ от точки $$$x=c$$$, то он находится в зоне покрытия сети, иначе — нет. Базовая станция может находится как на пути следования Поликарпа, так и вне его.</p><p>Выведите время в минутах, в течение которого Поликарп <span class="tex-font-style-bf">не будет</span> находится в зоне покрытия сети, при прямолинейном равномерном движении из $$$x=a$$$ в $$$x=b$$$. Его скорость движения — одна единица расстояния в минуту.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано положительное целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее записаны $$$t$$$ наборов входных данных.</p><p>Описание каждого набора входных данных составляет одну строку, которая содержит четыре целых числа $$$a$$$, $$$b$$$, $$$c$$$ и $$$r$$$ ($$$-10^8 \le a,b,c \le 10^8$$$, $$$0 \le r \le 10^8$$$) — координаты начальной и конечной точки пути, базовой станции и её радиус покрытия, соответственно.</p><p>Любые из чисел $$$a$$$, $$$b$$$ и $$$c$$$ могут совпадать (как любая пара, так и даже все три числа). Базовая станция может находится как на пути следования Поликарпа, так и вне его.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ чисел — ответы на заданные наборы входных данных в порядке их записи в тесте. Каждый ответ является целым числом — количество минут, в течение которых Поликарп будет <span class="tex-font-style-bf">недоступен</span> по сотовому телефону во время своего движения.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 9 1 10 7 1 3 3 3 0 8 2 10 4 8 2 10 100 -10 20 -17 2 -3 2 2 0 -3 1 2 0 2 3 2 3 -1 3 -2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 0 4 0 30 5 4 0 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Следующая картинка иллюстрирует первый набор входных данных примера.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/5ae358646600c8095c81107d2f3a7de5d5c04939.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Поликарп идёт из $$$1$$$ в $$$10$$$. Желтая область показывает зону покрытия вышки радиуса покрытия $$$1$$$, которая расположена в точке $$$7$$$. Зеленая область показывает ту часть пути, когда Поликарп находится вне зоны покрытия.</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="f34d617af0847e7e826a96959d8c2659"/> <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="ffd47bcd882b82e4d7d9030ecf8ffd9ed6eeaa55"/> <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='f34d617af0847e7e826a96959d8c2659'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1282%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='f34d617af0847e7e826a96959d8c2659'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1282">Codeforces Round 610 (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='f34d617af0847e7e826a96959d8c2659'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1282/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='f34d617af0847e7e826a96959d8c2659'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="502546"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f34d617af0847e7e826a96959d8c2659'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="502546"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72408" title="Codeforces Round #610 (Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10156:10157" 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/72461?locale=ru" title="72461" target="_blank">72461 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10167" resourceName="72461" resourceManual="true" src="//codeforces.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/72461?locale=en" title="72461" target="_blank">72461 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10166" resourceName="72461" resourceManual="true" src="//codeforces.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/1282">Задачи</a></li> <li><a href="/contest/1282/submit">Отослать</a></li> <li><a href="/contest/1282/my">Мои посылки</a></li> <li><a href="/contest/1282/status">Статус</a></li> <li><a href="/contest/1282/hacks">Взломы</a></li> <li><a href="/contest/1282/room/1">Комната</a></li> <li><a href="/contest/1282/standings">Положение</a></li> <li><a href="/contest/1282/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2c521b29e77b6ed5a0260191ec2612d106687303"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Поликарп живет на координатной оси $$$Ox$$$ и путешествует из точки $$$x=a$$$ в $$$x=b$$$. Он двигается равномерно прямолинейно со скоростью одна единица расстояния в минуту.</p><p>На оси $$$Ox$$$ в точке $$$x=c$$$ находится базовая станция оператора сотовой связи. Известно, что радиус её покрытия составляет $$$r$$$. Таким образом, если абонент находится на расстоянии меньшем или равном $$$r$$$ от точки $$$x=c$$$, то он находится в зоне покрытия сети, иначе — нет. Базовая станция может находится как на пути следования Поликарпа, так и вне его.</p><p>Выведите время в минутах, в течение которого Поликарп <span class="tex-font-style-bf">не будет</span> находится в зоне покрытия сети, при прямолинейном равномерном движении из $$$x=a$$$ в $$$x=b$$$. Его скорость движения — одна единица расстояния в минуту.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано положительное целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее записаны $$$t$$$ наборов входных данных.</p><p>Описание каждого набора входных данных составляет одну строку, которая содержит четыре целых числа $$$a$$$, $$$b$$$, $$$c$$$ и $$$r$$$ ($$$-10^8 \le a,b,c \le 10^8$$$, $$$0 \le r \le 10^8$$$) — координаты начальной и конечной точки пути, базовой станции и её радиус покрытия, соответственно.</p><p>Любые из чисел $$$a$$$, $$$b$$$ и $$$c$$$ могут совпадать (как любая пара, так и даже все три числа). Базовая станция может находится как на пути следования Поликарпа, так и вне его.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ чисел — ответы на заданные наборы входных данных в порядке их записи в тесте. Каждый ответ является целым числом — количество минут, в течение которых Поликарп будет <span class="tex-font-style-bf">недоступен</span> по сотовому телефону во время своего движения.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 9 1 10 7 1 3 3 3 0 8 2 10 4 8 2 10 100 -10 20 -17 2 -3 2 2 0 -3 1 2 0 2 3 2 3 -1 3 -2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 0 4 0 30 5 4 0 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Следующая картинка иллюстрирует первый набор входных данных примера.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/5ae358646600c8095c81107d2f3a7de5d5c04939.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Поликарп идёт из $$$1$$$ в $$$10$$$. Желтая область показывает зону покрытия вышки радиуса покрытия $$$1$$$, которая расположена в точке $$$7$$$. Зеленая область показывает ту часть пути, когда Поликарп находится вне зоны покрытия.</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:53: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:'8124928ee99900b0',t:'MTY5NjY2NTIyOC42OTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*900"]
1282B1
1282
B1
ru
B1. K по цене одного (простая версия)
<div class="problem-statement"><div class="header"><div class="title">B1. K по цене одного (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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">Это простая версия этой задачи. Единственное отличие в ограничении на $$$k$$$ — количество подарков в акции. В этой версии, $$$k=2$$$.</span></p><p>Вася пришел в магазин, чтобы купить подарки для своих друзей на Новый год. Оказалось, что ему очень повезло — именно сегодня в магазине проводится акция «$$$k$$$ товаров по цене одного». <span class="tex-font-style-bf">Помните, что в этой задаче $$$k=2$$$.</span></p><p>Благодаря этой акции Вася может купить ровно $$$k$$$ любых подарков, заплатив только за самый дорогой из них. Вася решил воспользоваться этой возможностью и купить как можно больше подарков для своих друзей на деньги, которые у него имеются.</p><p>Более формально, для каждого подарка определена его цена $$$a_i$$$ — количество монет, которое нужно потратить, чтобы приобрести этот подарок. Изначально, у Васи есть $$$p$$$ монет. Он хочет приобрести максимальное количество подарков. Вася может сколько угодно раз выполнить одну из следующих операций.</p><ul> <li> Вася может купить один любой подарок с номером $$$i$$$, если у него в настоящий момент достаточно монет (то есть $$$p \ge a_i$$$). После покупки этого подарка, количество монет у Васи уменьшится на величину $$$a_i$$$, то есть становится $$$p := p - a_i$$$. </li><li> Вася может купить подарок с номером $$$i$$$, а также выбрать еще ровно $$$k-1$$$ подарков, цены которых не превосходят $$$a_i$$$, если у него в настоящий момент достаточно монет (то есть $$$p \ge a_i$$$). Таким образом он покупает все эти $$$k$$$ подарков, а его количество монет уменьшается на величину $$$a_i$$$, то есть становится $$$p := p - a_i$$$. </li></ul><p>Обратите внимание, что каждый подарок можно приобрести не больше одного раза.</p><p>Например, если в магазине сейчас есть $$$n=5$$$ подарков, имеющих цены $$$a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$$$ соответственно, $$$k=2$$$, а у Васи есть $$$6$$$ монет, то он может купить суммарно $$$3$$$ подарка. Подарок с номером $$$1$$$ Вася купит, не используя акцию, и заплатит $$$2$$$ монеты. Подарки с номерами $$$2$$$ и $$$3$$$ Вася купит используя акцию, и заплатит $$$4$$$ монеты. Можно доказать, что приобрести больше подарков, имея шесть монет, Вася не может.</p><p>Помогите Васе узнать максимальное количество подарков, которые он может приобрести.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте.</p><p>Далее следуют описания $$$t$$$ наборов входных данных, по две строки на каждый набор.</p><p>В первой строке каждого набора входных данных содержится три целых числа $$$n, p, k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le p \le 2\cdot10^9$$$, $$$k=2$$$) — количество товаров в магазине, количество монет, имеющихся у Васи и количество товаров, которые можно купить по цене самого дорогого.</p><p>Во второй строке каждого набора данных находятся $$$n$$$ целых чисел $$$a_i$$$ ($$$1 \le a_i \le 10^4$$$) — цены подарков.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам данных не превосходит $$$2 \cdot 10^5$$$. <span class="tex-font-style-bf">Гарантируется, что в этой версии задачи $$$k=2$$$ для всех наборов входных данных.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора данных в отдельной строке выведите одно целое число $$$m$$$ — максимальное количество подарков, которые может купить Вася.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 5 6 2 2 4 3 5 7 5 11 2 2 4 3 5 7 2 10000 2 10000 10000 2 9999 2 10000 10000 5 13 2 8 2 8 2 5 3 18 2 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 2 0 4 3 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="fbea4b4190ea3085f9d2073570ba3110"/> <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="ffd47bcd882b82e4d7d9030ecf8ffd9ed6eeaa55"/> <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='fbea4b4190ea3085f9d2073570ba3110'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1282%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='fbea4b4190ea3085f9d2073570ba3110'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1282">Codeforces Round 610 (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='fbea4b4190ea3085f9d2073570ba3110'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1282/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='fbea4b4190ea3085f9d2073570ba3110'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="502547"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='fbea4b4190ea3085f9d2073570ba3110'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="502547"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72408" title="Codeforces Round #610 (Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10156:10157" 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/72461?locale=ru" title="72461" target="_blank">72461 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10167" resourceName="72461" resourceManual="true" src="//codeforces.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/72461?locale=en" title="72461" target="_blank">72461 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10166" resourceName="72461" resourceManual="true" src="//codeforces.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/1282">Задачи</a></li> <li><a href="/contest/1282/submit">Отослать</a></li> <li><a href="/contest/1282/my">Мои посылки</a></li> <li><a href="/contest/1282/status">Статус</a></li> <li><a href="/contest/1282/hacks">Взломы</a></li> <li><a href="/contest/1282/room/1">Комната</a></li> <li><a href="/contest/1282/standings">Положение</a></li> <li><a href="/contest/1282/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ce8d7367cd79c7b78663b597cd30cd9c3ef5070a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. K по цене одного (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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">Это простая версия этой задачи. Единственное отличие в ограничении на $$$k$$$ — количество подарков в акции. В этой версии, $$$k=2$$$.</span></p><p>Вася пришел в магазин, чтобы купить подарки для своих друзей на Новый год. Оказалось, что ему очень повезло — именно сегодня в магазине проводится акция «$$$k$$$ товаров по цене одного». <span class="tex-font-style-bf">Помните, что в этой задаче $$$k=2$$$.</span></p><p>Благодаря этой акции Вася может купить ровно $$$k$$$ любых подарков, заплатив только за самый дорогой из них. Вася решил воспользоваться этой возможностью и купить как можно больше подарков для своих друзей на деньги, которые у него имеются.</p><p>Более формально, для каждого подарка определена его цена $$$a_i$$$ — количество монет, которое нужно потратить, чтобы приобрести этот подарок. Изначально, у Васи есть $$$p$$$ монет. Он хочет приобрести максимальное количество подарков. Вася может сколько угодно раз выполнить одну из следующих операций.</p><ul> <li> Вася может купить один любой подарок с номером $$$i$$$, если у него в настоящий момент достаточно монет (то есть $$$p \ge a_i$$$). После покупки этого подарка, количество монет у Васи уменьшится на величину $$$a_i$$$, то есть становится $$$p := p - a_i$$$. </li><li> Вася может купить подарок с номером $$$i$$$, а также выбрать еще ровно $$$k-1$$$ подарков, цены которых не превосходят $$$a_i$$$, если у него в настоящий момент достаточно монет (то есть $$$p \ge a_i$$$). Таким образом он покупает все эти $$$k$$$ подарков, а его количество монет уменьшается на величину $$$a_i$$$, то есть становится $$$p := p - a_i$$$. </li></ul><p>Обратите внимание, что каждый подарок можно приобрести не больше одного раза.</p><p>Например, если в магазине сейчас есть $$$n=5$$$ подарков, имеющих цены $$$a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$$$ соответственно, $$$k=2$$$, а у Васи есть $$$6$$$ монет, то он может купить суммарно $$$3$$$ подарка. Подарок с номером $$$1$$$ Вася купит, не используя акцию, и заплатит $$$2$$$ монеты. Подарки с номерами $$$2$$$ и $$$3$$$ Вася купит используя акцию, и заплатит $$$4$$$ монеты. Можно доказать, что приобрести больше подарков, имея шесть монет, Вася не может.</p><p>Помогите Васе узнать максимальное количество подарков, которые он может приобрести.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте.</p><p>Далее следуют описания $$$t$$$ наборов входных данных, по две строки на каждый набор.</p><p>В первой строке каждого набора входных данных содержится три целых числа $$$n, p, k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le p \le 2\cdot10^9$$$, $$$k=2$$$) — количество товаров в магазине, количество монет, имеющихся у Васи и количество товаров, которые можно купить по цене самого дорогого.</p><p>Во второй строке каждого набора данных находятся $$$n$$$ целых чисел $$$a_i$$$ ($$$1 \le a_i \le 10^4$$$) — цены подарков.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам данных не превосходит $$$2 \cdot 10^5$$$. <span class="tex-font-style-bf">Гарантируется, что в этой версии задачи $$$k=2$$$ для всех наборов входных данных.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора данных в отдельной строке выведите одно целое число $$$m$$$ — максимальное количество подарков, которые может купить Вася.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 5 6 2 2 4 3 5 7 5 11 2 2 4 3 5 7 2 10000 2 10000 10000 2 9999 2 10000 10000 5 13 2 8 2 8 2 5 3 18 2 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 2 0 4 3 </pre></div></div></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:53: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:'8124929708997b3f',t:'MTY5NjY2NTIzMC4wOTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1400"]
1282B2
1282
B2
ru
B2. K по цене одного (усложнённая версия)
<div class="problem-statement"><div class="header"><div class="title">B2. K по цене одного (усложнённая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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">Это сложная версия этой задачи. Единственное отличие в ограничении на $$$k$$$ —количество подарков в акции. В этой версии $$$2 \le k \le n$$$.</span></p><p>Вася пришел в магазин, чтобы купить подарки для своих друзей на Новый год. Оказалось, что ему очень повезло — именно сегодня в магазине проводится акция «$$$k$$$ товаров по цене одного».</p><p>Благодаря этой акции Вася может купить <span class="tex-font-style-bf">ровно</span> $$$k$$$ любых подарков, заплатив только за самый дорогой из них. Вася решил воспользоваться этой возможностью и купить как можно больше подарков для своих друзей на деньги, которые у него имеются.</p><p>Более формально, для каждого подарка определена его цена $$$a_i$$$ — количество монет, которое нужно потратить, чтобы приобрести этот подарок. Изначально, у Васи есть $$$p$$$ монет. Он хочет приобрести максимальное количество подарков. Вася может сколько угодно раз выполнить одну из следующих операций.</p><ul> <li> Вася может купить один любой подарок с номером $$$i$$$, если у него в настоящий момент достаточно монет (то есть $$$p \ge a_i$$$). После покупки этого подарка, количество монет у Васи уменьшится на величину $$$a_i$$$, то есть становится $$$p := p - a_i$$$. </li><li> Вася может купить подарок с номером $$$i$$$, а также выбрать еще ровно $$$k-1$$$ подарков, цены которых не превосходят $$$a_i$$$, если у него в настоящий момент достаточно монет (то есть $$$p \ge a_i$$$). Таким образом он покупает все эти $$$k$$$ подарков, а его количество монет уменьшается на величину $$$a_i$$$, то есть становится $$$p := p - a_i$$$. </li></ul><p>Обратите внимание, что каждый подарок можно приобрести не больше одного раза.</p><p>Например, если в магазине сейчас есть $$$n=5$$$ подарков, имеющих цены $$$a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$$$ соответственно, $$$k=2$$$, а у Васи есть $$$6$$$ монет, то он может купить суммарно $$$3$$$ подарка. Подарок с номером $$$1$$$ Вася купит, не используя акцию, и заплатит $$$2$$$ монеты. Подарки с номерами $$$2$$$ и $$$3$$$ Вася купит используя акцию, и заплатит $$$4$$$ монеты. Можно доказать, что приобрести больше подарков, имея шесть монет, Вася не может.</p><p>Помогите Васе узнать максимальное количество подарков, которые он может приобрести.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте.</p><p>Далее следуют описания $$$t$$$ наборов входных данных, по две строки на каждый набор.</p><p>В первой строке каждого набора входных данных содержится три целых числа $$$n, p, k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le p \le 2\cdot10^9$$$, $$$2 \le k \le n$$$) — количество товаров в магазине, количество монет, имеющихся у Васи и количество товаров, которые можно купить по цене самого дорогого.</p><p>Во второй строке каждого набора данных находятся $$$n$$$ целых чисел $$$a_i$$$ ($$$1 \le a_i \le 10^4$$$) — цены подарков.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора данных в отдельной строке выведите одно целое число $$$m$$$ — максимальное количество подарков, которые может купить Вася.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 5 6 2 2 4 3 5 7 5 11 2 2 4 3 5 7 3 2 3 4 2 6 5 2 3 10 1 3 9 2 2 10000 2 10000 10000 2 9999 2 10000 10000 4 6 4 3 2 3 2 5 5 3 1 2 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 1 1 2 0 4 5 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="e2747de0db96459ffe9057046a19563c"/> <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="ffd47bcd882b82e4d7d9030ecf8ffd9ed6eeaa55"/> <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='e2747de0db96459ffe9057046a19563c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1282%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='e2747de0db96459ffe9057046a19563c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1282">Codeforces Round 610 (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='e2747de0db96459ffe9057046a19563c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1282/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='e2747de0db96459ffe9057046a19563c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="502548"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e2747de0db96459ffe9057046a19563c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="502548"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72408" title="Codeforces Round #610 (Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10156:10157" 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/72461?locale=ru" title="72461" target="_blank">72461 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10167" resourceName="72461" resourceManual="true" src="//codeforces.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/72461?locale=en" title="72461" target="_blank">72461 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10166" resourceName="72461" resourceManual="true" src="//codeforces.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/1282">Задачи</a></li> <li><a href="/contest/1282/submit">Отослать</a></li> <li><a href="/contest/1282/my">Мои посылки</a></li> <li><a href="/contest/1282/status">Статус</a></li> <li><a href="/contest/1282/hacks">Взломы</a></li> <li><a href="/contest/1282/room/1">Комната</a></li> <li><a href="/contest/1282/standings">Положение</a></li> <li><a href="/contest/1282/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ec1470462d06a5e6f1a26f1fcd78845354fa014c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. K по цене одного (усложнённая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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">Это сложная версия этой задачи. Единственное отличие в ограничении на $$$k$$$ —количество подарков в акции. В этой версии $$$2 \le k \le n$$$.</span></p><p>Вася пришел в магазин, чтобы купить подарки для своих друзей на Новый год. Оказалось, что ему очень повезло — именно сегодня в магазине проводится акция «$$$k$$$ товаров по цене одного».</p><p>Благодаря этой акции Вася может купить <span class="tex-font-style-bf">ровно</span> $$$k$$$ любых подарков, заплатив только за самый дорогой из них. Вася решил воспользоваться этой возможностью и купить как можно больше подарков для своих друзей на деньги, которые у него имеются.</p><p>Более формально, для каждого подарка определена его цена $$$a_i$$$ — количество монет, которое нужно потратить, чтобы приобрести этот подарок. Изначально, у Васи есть $$$p$$$ монет. Он хочет приобрести максимальное количество подарков. Вася может сколько угодно раз выполнить одну из следующих операций.</p><ul> <li> Вася может купить один любой подарок с номером $$$i$$$, если у него в настоящий момент достаточно монет (то есть $$$p \ge a_i$$$). После покупки этого подарка, количество монет у Васи уменьшится на величину $$$a_i$$$, то есть становится $$$p := p - a_i$$$. </li><li> Вася может купить подарок с номером $$$i$$$, а также выбрать еще ровно $$$k-1$$$ подарков, цены которых не превосходят $$$a_i$$$, если у него в настоящий момент достаточно монет (то есть $$$p \ge a_i$$$). Таким образом он покупает все эти $$$k$$$ подарков, а его количество монет уменьшается на величину $$$a_i$$$, то есть становится $$$p := p - a_i$$$. </li></ul><p>Обратите внимание, что каждый подарок можно приобрести не больше одного раза.</p><p>Например, если в магазине сейчас есть $$$n=5$$$ подарков, имеющих цены $$$a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$$$ соответственно, $$$k=2$$$, а у Васи есть $$$6$$$ монет, то он может купить суммарно $$$3$$$ подарка. Подарок с номером $$$1$$$ Вася купит, не используя акцию, и заплатит $$$2$$$ монеты. Подарки с номерами $$$2$$$ и $$$3$$$ Вася купит используя акцию, и заплатит $$$4$$$ монеты. Можно доказать, что приобрести больше подарков, имея шесть монет, Вася не может.</p><p>Помогите Васе узнать максимальное количество подарков, которые он может приобрести.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте.</p><p>Далее следуют описания $$$t$$$ наборов входных данных, по две строки на каждый набор.</p><p>В первой строке каждого набора входных данных содержится три целых числа $$$n, p, k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le p \le 2\cdot10^9$$$, $$$2 \le k \le n$$$) — количество товаров в магазине, количество монет, имеющихся у Васи и количество товаров, которые можно купить по цене самого дорогого.</p><p>Во второй строке каждого набора данных находятся $$$n$$$ целых чисел $$$a_i$$$ ($$$1 \le a_i \le 10^4$$$) — цены подарков.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора данных в отдельной строке выведите одно целое число $$$m$$$ — максимальное количество подарков, которые может купить Вася.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 5 6 2 2 4 3 5 7 5 11 2 2 4 3 5 7 3 2 3 4 2 6 5 2 3 10 1 3 9 2 2 10000 2 10000 10000 2 9999 2 10000 10000 4 6 4 3 2 3 2 5 5 3 1 2 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 1 1 2 0 4 5 </pre></div></div></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:53: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:'8124929fedbb163d',t:'MTY5NjY2NTIzMS44MDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1600"]
1282C
1282
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$$$ задач, которые можно решать в течении $$$T$$$ минут. Таким образом, экзамен начинается в момент времени $$$0$$$, а заканчивается — в момент времени $$$T$$$. Петя может уйти с экзамена в любой целочисленный момент времени от $$$0$$$ до $$$T$$$, включительно.</p><p>Все задачи делятся на два типа: </p><ul> <li> простые задачи — на решение каждой простой задачи у Пети уходит ровно $$$a$$$ минут; </li><li> сложные задачи — на решение каждой сложной задачи у Пети уходит ровно $$$b$$$ минут ($$$b &gt; a$$$). </li></ul><p>Таким образом, если в момент времени $$$x$$$ Петя приступает к решению простой задачи, то она будет решена в момент времени $$$x+a$$$. Аналогично, если в момент времени $$$x$$$ Петя приступает к решению сложной задачи, то она будет решена в момент времени $$$x+b$$$.</p><p>Про каждую задачу Пете известно сложная она или простая. Помимо этого, для каждой задачи определен момент времени $$$t_i$$$ ($$$0 \le t_i \le T$$$), в который она станет обязательной. Если Петя уходит с экзамена в момент времени $$$s$$$ и есть такая задача $$$i$$$, что $$$t_i \le s$$$ и он её не решил, то считается, что за весь экзамен он получит $$$0$$$ баллов. В противном случае (то есть, если он решил все такие задачи, для которых $$$t_i \le s$$$) он получит количество баллов, равное количеству решенных задач. Отметим, что уходя в момент времени $$$s$$$ Петя может иметь решенными как «обязательные», так и «необязательные» задачи.</p><p>Например, если $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, первая задача является сложной и для неё $$$t_1=3$$$ и вторая задача является простой и для неё $$$t_2=2$$$, то:</p><ul> <li> если он уходит в момент времени $$$s=0$$$, то он получит $$$0$$$ баллов, так как не успеет решить ни одной задачи; </li><li> если он уходит в момент времени $$$s=1$$$, то он получит $$$0$$$ баллов, так как не успеет решить ни одной задачи; </li><li> если он уходит в момент времени $$$s=2$$$, то он может получить $$$1$$$ балл, решив задачу с номером $$$2$$$ (решать её надо в промежуток от $$$0$$$ до $$$2$$$); </li><li> если он уходит в момент времени $$$s=3$$$, то он получит $$$0$$$ баллов, так как к этому моменту времени обе задачи станут обязательными к решению, но решить их обе он не успеет; </li><li> если он уходит в момент времени $$$s=4$$$, то он получит $$$0$$$ баллов, так как к этому моменту времени обе задачи станут обязательными к решению, но решить их обе он не успеет; </li><li> если он уходит в момент времени $$$s=5$$$, то он может получить $$$2$$$ балла, решив все задачи. </li></ul><p>Таким образом, ответ на этот тест равен $$$2$$$.</p><p>Помогите Пете определить максимальное количество баллов, которые он успеет набрать перед тем как уйдет с экзамена.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится число $$$m$$$ ($$$1 \le m \le 10^4$$$) — количество наборов входных данных в тесте.</p><p>Далее следуют описания $$$m$$$ наборов входных данных, по три строки на каждый набор.</p><p>В первой строке каждого набора входных данных находятся четыре целых числа $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a &lt; b \le 10^9$$$) — количество задач, минут, отведенных на экзамен, время решения простой и сложной задачи, соответственно.</p><p>Во второй строке каждого набора входных данных находятся $$$n$$$ чисел $$$0$$$ или $$$1$$$, записанные через пробел: $$$i$$$-е число означает тип $$$i$$$-й задачи. Значение $$$0$$$ означает, что задача простая, а значение $$$1$$$ — сложная.</p><p>В третьей строке каждого набора входных данных находятся $$$n$$$ целых чисел $$$t_i$$$ ($$$0 \le t_i \le T$$$), где $$$i$$$-е число означает время, в которое $$$i$$$-я задача станет обязательной.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2\cdot10^5$$$</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответы на $$$m$$$ заданных наборов входных данных. Для каждого набора выведите одно целое число — максимальное количество баллов, которые он успеет набрать перед тем как уйдет с экзамена.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 10 3 5 1 3 0 0 1 2 1 4 2 5 2 3 1 0 3 2 1 20 2 4 0 16 6 20 2 5 1 1 0 1 0 0 0 8 2 9 11 6 4 16 3 6 1 0 1 1 8 3 5 6 6 20 3 6 0 1 0 0 1 0 20 11 3 20 16 17 7 17 1 6 1 1 0 1 0 0 0 1 7 0 11 10 15 10 6 17 2 6 0 0 1 0 0 1 7 6 3 7 10 12 5 17 2 5 1 1 1 1 0 17 11 10 6 4 1 1 1 2 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 1 0 1 4 0 1 2 1 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="8bd4ee71f66fd0db2d41e976a89d6794"/> <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="ffd47bcd882b82e4d7d9030ecf8ffd9ed6eeaa55"/> <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='8bd4ee71f66fd0db2d41e976a89d6794'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1282%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='8bd4ee71f66fd0db2d41e976a89d6794'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1282">Codeforces Round 610 (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='8bd4ee71f66fd0db2d41e976a89d6794'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1282/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='8bd4ee71f66fd0db2d41e976a89d6794'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="502549"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8bd4ee71f66fd0db2d41e976a89d6794'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="502549"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72408" title="Codeforces Round #610 (Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10156:10157" 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/72461?locale=ru" title="72461" target="_blank">72461 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10167" resourceName="72461" resourceManual="true" src="//codeforces.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/72461?locale=en" title="72461" target="_blank">72461 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10166" resourceName="72461" resourceManual="true" src="//codeforces.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/1282">Задачи</a></li> <li><a href="/contest/1282/submit">Отослать</a></li> <li><a href="/contest/1282/my">Мои посылки</a></li> <li><a href="/contest/1282/status">Статус</a></li> <li><a href="/contest/1282/hacks">Взломы</a></li> <li><a href="/contest/1282/room/1">Комната</a></li> <li><a href="/contest/1282/standings">Положение</a></li> <li><a href="/contest/1282/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_68fbdec285036dc3de2af17b52952b38c7b260ab"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ задач, которые можно решать в течении $$$T$$$ минут. Таким образом, экзамен начинается в момент времени $$$0$$$, а заканчивается — в момент времени $$$T$$$. Петя может уйти с экзамена в любой целочисленный момент времени от $$$0$$$ до $$$T$$$, включительно.</p><p>Все задачи делятся на два типа: </p><ul> <li> простые задачи — на решение каждой простой задачи у Пети уходит ровно $$$a$$$ минут; </li><li> сложные задачи — на решение каждой сложной задачи у Пети уходит ровно $$$b$$$ минут ($$$b &gt; a$$$). </li></ul><p>Таким образом, если в момент времени $$$x$$$ Петя приступает к решению простой задачи, то она будет решена в момент времени $$$x+a$$$. Аналогично, если в момент времени $$$x$$$ Петя приступает к решению сложной задачи, то она будет решена в момент времени $$$x+b$$$.</p><p>Про каждую задачу Пете известно сложная она или простая. Помимо этого, для каждой задачи определен момент времени $$$t_i$$$ ($$$0 \le t_i \le T$$$), в который она станет обязательной. Если Петя уходит с экзамена в момент времени $$$s$$$ и есть такая задача $$$i$$$, что $$$t_i \le s$$$ и он её не решил, то считается, что за весь экзамен он получит $$$0$$$ баллов. В противном случае (то есть, если он решил все такие задачи, для которых $$$t_i \le s$$$) он получит количество баллов, равное количеству решенных задач. Отметим, что уходя в момент времени $$$s$$$ Петя может иметь решенными как «обязательные», так и «необязательные» задачи.</p><p>Например, если $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, первая задача является сложной и для неё $$$t_1=3$$$ и вторая задача является простой и для неё $$$t_2=2$$$, то:</p><ul> <li> если он уходит в момент времени $$$s=0$$$, то он получит $$$0$$$ баллов, так как не успеет решить ни одной задачи; </li><li> если он уходит в момент времени $$$s=1$$$, то он получит $$$0$$$ баллов, так как не успеет решить ни одной задачи; </li><li> если он уходит в момент времени $$$s=2$$$, то он может получить $$$1$$$ балл, решив задачу с номером $$$2$$$ (решать её надо в промежуток от $$$0$$$ до $$$2$$$); </li><li> если он уходит в момент времени $$$s=3$$$, то он получит $$$0$$$ баллов, так как к этому моменту времени обе задачи станут обязательными к решению, но решить их обе он не успеет; </li><li> если он уходит в момент времени $$$s=4$$$, то он получит $$$0$$$ баллов, так как к этому моменту времени обе задачи станут обязательными к решению, но решить их обе он не успеет; </li><li> если он уходит в момент времени $$$s=5$$$, то он может получить $$$2$$$ балла, решив все задачи. </li></ul><p>Таким образом, ответ на этот тест равен $$$2$$$.</p><p>Помогите Пете определить максимальное количество баллов, которые он успеет набрать перед тем как уйдет с экзамена.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится число $$$m$$$ ($$$1 \le m \le 10^4$$$) — количество наборов входных данных в тесте.</p><p>Далее следуют описания $$$m$$$ наборов входных данных, по три строки на каждый набор.</p><p>В первой строке каждого набора входных данных находятся четыре целых числа $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a &lt; b \le 10^9$$$) — количество задач, минут, отведенных на экзамен, время решения простой и сложной задачи, соответственно.</p><p>Во второй строке каждого набора входных данных находятся $$$n$$$ чисел $$$0$$$ или $$$1$$$, записанные через пробел: $$$i$$$-е число означает тип $$$i$$$-й задачи. Значение $$$0$$$ означает, что задача простая, а значение $$$1$$$ — сложная.</p><p>В третьей строке каждого набора входных данных находятся $$$n$$$ целых чисел $$$t_i$$$ ($$$0 \le t_i \le T$$$), где $$$i$$$-е число означает время, в которое $$$i$$$-я задача станет обязательной.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2\cdot10^5$$$</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответы на $$$m$$$ заданных наборов входных данных. Для каждого набора выведите одно целое число — максимальное количество баллов, которые он успеет набрать перед тем как уйдет с экзамена.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 10 3 5 1 3 0 0 1 2 1 4 2 5 2 3 1 0 3 2 1 20 2 4 0 16 6 20 2 5 1 1 0 1 0 0 0 8 2 9 11 6 4 16 3 6 1 0 1 1 8 3 5 6 6 20 3 6 0 1 0 0 1 0 20 11 3 20 16 17 7 17 1 6 1 1 0 1 0 0 0 1 7 0 11 10 15 10 6 17 2 6 0 0 1 0 0 1 7 6 3 7 10 12 5 17 2 5 1 1 1 1 0 17 11 10 6 4 1 1 1 2 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 1 0 1 4 0 1 2 1 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:53:53</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'812492aa7c269d70',t:'MTY5NjY2NTIzMy4yMDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1800"]
1282D
1282
D
ru
D. Заколдованный артефакт
<div class="problem-statement"><div class="header"><div class="title">D. Заколдованный артефакт</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача.</span> </p><p>Пройдя последний уровень зачарованного храма, вы получили могущественный артефакт 255-го уровня. Не стоит спешить радоваться, ведь на данном артефакте установлена мощная руна, которую можно разрушить единственным секретным <span class="tex-font-style-it">заклинанием</span> $$$s$$$. Именно это заклинание вам и предстоит найти.</p><p>Определим заклинание как некоторую <span class="tex-font-style-bf">непустую строку</span>, состоящую только из букв <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>.</p><p>В любой момент времени Вы можете произнести произвольное непустое заклинание $$$t$$$, при этом руна на артефакте начнёт сопротивляться. <span class="tex-font-style-it">Сопротивлением</span> руны называется <span class="tex-font-style-it">редакционное расстояние</span> между строками, задающих произнесённое заклинание $$$t$$$ и искомое секретное заклинание $$$s$$$, при произнесении которого руна разрушается. </p><p><a href="http://gg.gg/levenshtein-dist-ru">Редакционным расстоянием</a> двух строк $$$s$$$ и $$$t$$$ называется величина, равная минимальному количеству односимвольных операций замены, вставки и удаления символов в $$$s$$$ для получения $$$t$$$. К примеру, расстояние между <span class="tex-font-style-tt">ababa</span> и <span class="tex-font-style-tt">aaa</span> равно $$$2$$$, <span class="tex-font-style-tt">aaa</span> и <span class="tex-font-style-tt">aba</span> — $$$1$$$, <span class="tex-font-style-tt">bbaba</span> и <span class="tex-font-style-tt">abb</span> — $$$3$$$. Редакционное расстояние равно $$$0$$$ тогда и только тогда, когда строки равны.</p><p>Также стоит учитывать, что у артефакта есть предел сопротивляемости — если вы произнесёте более чем $$$n + 2$$$ заклинаний, где $$$n$$$ — это длина заклинания $$$s$$$, то руна заблокируется. </p><p>Таким образом, требуется за $$$n + 2$$$ или меньшее количество заклинаний разрушить руну, находящуюся на Вашем артефакте. Следует учитывать, что искомое разрушающее заклинание $$$s$$$ также должно быть учтено среди этих $$$n + 2$$$ заклинаний.</p><p>Учтите, что длина $$$n$$$ разрушающего руну заклинания $$$s$$$ вам заранее не известна. Известно только то, что его длина $$$n$$$ не превосходит $$$300$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Взаимодействие происходит с помощью запросов. </p><p>Каждый запрос состоит из единственной <span class="tex-font-style-bf">непустой</span> строки $$$t$$$ — заклинания, которое вы хотите произнести. Длина строки $$$t$$$ не должна превышать $$$300$$$. Строка должна состоять только из букв <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>.</p><p>В ответ на запрос вы получите <span class="tex-font-style-it">сопротивление</span> руны — редакционное расстояние между строками, задающих произнесённое заклинание $$$t$$$ и искомое заклинание $$$s$$$, при произнесении которого руна разрушается. Помните, что $$$s$$$ содержит только буквы <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>.</p><p>После разрушения руны ваша программа должна немедленно завершиться. Руна разрушается, если её сопротивление достигает значения $$$0$$$. После получения значения $$$0$$$ ваша программа должна завершиться штатным образом.</p><p>В этой задаче интерактор <span class="tex-font-style-bf">не адаптивный</span>. Это означает, что в рамках одного теста искомое заклинание $$$s$$$ <span class="tex-font-style-bf">не меняется</span>.</p><p>При некорректном запросе будет выведено <span class="tex-font-style-tt">-1</span>. При получении данного значения ваша программа должна немедленно завершиться штатным образом (к примеру, с помощью вызова <span class="tex-font-style-tt">exit(0)</span>), иначе тестирующая система может выдать произвольный вердикт.</p><p>При превышении количества заклинаний (то есть числа $$$n + 2$$$, где $$$n$$$ — длина заклинания $$$s$$$, это число вам неизвестно) будет выведен вердикт <span class="tex-font-style-it">неправильный ответ</span>.</p><p>Ваше решение может получить вердикт <span class="tex-font-style-it">Решение «зависло»</span>, если вы ничего не выведете или забудете сбросить буфер вывода.</p><p>Чтобы сбросить буфер вывода вам нужно сделать следующее сразу после вывода запроса и символа конца строки:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> см. документацию других языков. </li></ul><p><span class="tex-font-style-bf">Взломы</span></p><p>Используйте следующий формат для взломов:</p><p>В единственной строке выведите строку $$$s$$$ ($$$1 \le |s| \le 300$$$) из букв <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>, задающую разрушающее заклинание. </p><p>Взламываемое решение не будет иметь прямого доступа к загаданной строке.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 1 2 3 0</pre></div><div class="output"><div class="title">Выходные данные</div><pre> aaa aaab abba bba abaaa aabba</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="fac1b0a148d6cbec95d988d27dae9ea3"/> <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="ffd47bcd882b82e4d7d9030ecf8ffd9ed6eeaa55"/> <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='fac1b0a148d6cbec95d988d27dae9ea3'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1282%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='fac1b0a148d6cbec95d988d27dae9ea3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1282">Codeforces Round 610 (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='fac1b0a148d6cbec95d988d27dae9ea3'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1282/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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="Сложность"> *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='fac1b0a148d6cbec95d988d27dae9ea3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="502551"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='fac1b0a148d6cbec95d988d27dae9ea3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="502551"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72408" title="Codeforces Round #610 (Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10156:10157" 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/72461?locale=ru" title="72461" target="_blank">72461 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10167" resourceName="72461" resourceManual="true" src="//codeforces.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/72461?locale=en" title="72461" target="_blank">72461 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10166" resourceName="72461" resourceManual="true" src="//codeforces.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/1282">Задачи</a></li> <li><a href="/contest/1282/submit">Отослать</a></li> <li><a href="/contest/1282/my">Мои посылки</a></li> <li><a href="/contest/1282/status">Статус</a></li> <li><a href="/contest/1282/hacks">Взломы</a></li> <li><a href="/contest/1282/room/1">Комната</a></li> <li><a href="/contest/1282/standings">Положение</a></li> <li><a href="/contest/1282/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_3182d7212e08eac08d52a73fe09b900e527fc2d6"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Заколдованный артефакт</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача.</span> </p><p>Пройдя последний уровень зачарованного храма, вы получили могущественный артефакт 255-го уровня. Не стоит спешить радоваться, ведь на данном артефакте установлена мощная руна, которую можно разрушить единственным секретным <span class="tex-font-style-it">заклинанием</span> $$$s$$$. Именно это заклинание вам и предстоит найти.</p><p>Определим заклинание как некоторую <span class="tex-font-style-bf">непустую строку</span>, состоящую только из букв <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>.</p><p>В любой момент времени Вы можете произнести произвольное непустое заклинание $$$t$$$, при этом руна на артефакте начнёт сопротивляться. <span class="tex-font-style-it">Сопротивлением</span> руны называется <span class="tex-font-style-it">редакционное расстояние</span> между строками, задающих произнесённое заклинание $$$t$$$ и искомое секретное заклинание $$$s$$$, при произнесении которого руна разрушается. </p><p><a href="http://gg.gg/levenshtein-dist-ru">Редакционным расстоянием</a> двух строк $$$s$$$ и $$$t$$$ называется величина, равная минимальному количеству односимвольных операций замены, вставки и удаления символов в $$$s$$$ для получения $$$t$$$. К примеру, расстояние между <span class="tex-font-style-tt">ababa</span> и <span class="tex-font-style-tt">aaa</span> равно $$$2$$$, <span class="tex-font-style-tt">aaa</span> и <span class="tex-font-style-tt">aba</span> — $$$1$$$, <span class="tex-font-style-tt">bbaba</span> и <span class="tex-font-style-tt">abb</span> — $$$3$$$. Редакционное расстояние равно $$$0$$$ тогда и только тогда, когда строки равны.</p><p>Также стоит учитывать, что у артефакта есть предел сопротивляемости — если вы произнесёте более чем $$$n + 2$$$ заклинаний, где $$$n$$$ — это длина заклинания $$$s$$$, то руна заблокируется. </p><p>Таким образом, требуется за $$$n + 2$$$ или меньшее количество заклинаний разрушить руну, находящуюся на Вашем артефакте. Следует учитывать, что искомое разрушающее заклинание $$$s$$$ также должно быть учтено среди этих $$$n + 2$$$ заклинаний.</p><p>Учтите, что длина $$$n$$$ разрушающего руну заклинания $$$s$$$ вам заранее не известна. Известно только то, что его длина $$$n$$$ не превосходит $$$300$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Взаимодействие происходит с помощью запросов. </p><p>Каждый запрос состоит из единственной <span class="tex-font-style-bf">непустой</span> строки $$$t$$$ — заклинания, которое вы хотите произнести. Длина строки $$$t$$$ не должна превышать $$$300$$$. Строка должна состоять только из букв <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>.</p><p>В ответ на запрос вы получите <span class="tex-font-style-it">сопротивление</span> руны — редакционное расстояние между строками, задающих произнесённое заклинание $$$t$$$ и искомое заклинание $$$s$$$, при произнесении которого руна разрушается. Помните, что $$$s$$$ содержит только буквы <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>.</p><p>После разрушения руны ваша программа должна немедленно завершиться. Руна разрушается, если её сопротивление достигает значения $$$0$$$. После получения значения $$$0$$$ ваша программа должна завершиться штатным образом.</p><p>В этой задаче интерактор <span class="tex-font-style-bf">не адаптивный</span>. Это означает, что в рамках одного теста искомое заклинание $$$s$$$ <span class="tex-font-style-bf">не меняется</span>.</p><p>При некорректном запросе будет выведено <span class="tex-font-style-tt">-1</span>. При получении данного значения ваша программа должна немедленно завершиться штатным образом (к примеру, с помощью вызова <span class="tex-font-style-tt">exit(0)</span>), иначе тестирующая система может выдать произвольный вердикт.</p><p>При превышении количества заклинаний (то есть числа $$$n + 2$$$, где $$$n$$$ — длина заклинания $$$s$$$, это число вам неизвестно) будет выведен вердикт <span class="tex-font-style-it">неправильный ответ</span>.</p><p>Ваше решение может получить вердикт <span class="tex-font-style-it">Решение «зависло»</span>, если вы ничего не выведете или забудете сбросить буфер вывода.</p><p>Чтобы сбросить буфер вывода вам нужно сделать следующее сразу после вывода запроса и символа конца строки:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> см. документацию других языков. </li></ul><p><span class="tex-font-style-bf">Взломы</span></p><p>Используйте следующий формат для взломов:</p><p>В единственной строке выведите строку $$$s$$$ ($$$1 \le |s| \le 300$$$) из букв <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>, задающую разрушающее заклинание. </p><p>Взламываемое решение не будет иметь прямого доступа к загаданной строке.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 1 2 3 0</pre></div><div class="output"><div class="title">Выходные данные</div><pre> aaa aaab abba bba abaaa aabba</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:53: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:'812492b32d749d84',t:'MTY5NjY2NTIzNC43NTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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"]
["\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u0442\u0440\u043e\u043a\u0438", "*2300"]
1282E
1282
E
ru
E. Тортик - ложь
<div class="problem-statement"><div class="header"><div class="title">E. Тортик - ложь</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Мы заботимся о моральном состоянии участников соревнования. Поэтому вместо задачи мы предлагаем вам полакомиться кусочком торта.</span></p><p><span class="tex-font-style-it">Ох, кто-то уже разрезал торт! Мы просили их дождаться вас, но они не послушали. Если поторопитесь, успеете взять кусочек. Вы, конечно, перед тем, как попробовать торт, задумались, как торт был разрезан.</span></p><p>Известно, что торт изначально представлял собой правильный $$$n$$$-угольник, каждая вершина которого имела уникальный номер от $$$1$$$ до $$$n$$$. Вершины были пронумерованы в некотором произвольном порядке.</p><p>Каждый кусок торта — это треугольник. Торт разрезали на $$$n - 2$$$ куска следующим образом: каждый раз проводили один разрез ножом (от вершины до вершины) такой, что от текущего торта отделялся ровно один треугольный кусок, а оставшаяся часть продолжала составлять выпуклый многоугольник. Иными словами, каждый раз выбирали три подряд идущие вершины многоугольника и отрезали соответствующий треугольник.</p><p>Возможный процесс разрезания торта представлен на рисунке ниже.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6bf414b22f71f67fe022c91f039ead6674986c6c.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Пример разрезания 6-угольного торта.</span> </center><p>Вам задан набор получившихся $$$n-2$$$ треугольных кусочков в произвольном порядке. Вершины каждого из кусочков записаны в произвольном порядке — по или против часовой стрелки. Каждый кусочек задается тремя числами — номерами соответствующих ему вершин $$$n$$$-угольного торта.</p><p>Например, для ситуации с рисунком выше вам мог быть задан набор кусочков: $$$[3, 6, 5], [5, 2, 4], [5, 4, 6], [6, 3, 1]$$$.</p><p>Вас интересуют два вопроса.</p><ul> <li> Какая была нумерация вершин $$$n$$$-угольного торта? </li><li> В каком порядке отрезались кусочки? </li></ul><p>Формально, вам предстоит найти две перестановки $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) и $$$q_1, q_2, \dots, q_{n - 2}$$$ ($$$1 \le q_i \le n - 2$$$) такие, что если вершины торта пронумерованы числами $$$p_1, p_2, \dots, p_n$$$ в порядке по или против часовой стрелки, то при отрезании кусков торта в порядке $$$q_1, q_2, \dots, q_{n - 2}$$$ всегда отрезается треугольный кусок так, что оставшаяся часть образует один выпуклый многоугольник.</p><p>Например, для рисунка выше искомыми перестановками могли бы быть: $$$p=[2, 4, 6, 1, 3, 5]$$$ (или любой её циклический сдвиг, или её переворот и после этого любой циклический сдвиг) и $$$q=[2, 4, 1, 3]$$$.</p><p>Напишите программу, которая по заданным треугольным кусочкам находит любую подходящую пару перестановок $$$p$$$ и $$$q$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных. Далее следуют $$$t$$$ независимых наборов входных данных.</p><p>Первая строка каждого набора состоит из одного целого числа $$$n$$$ ($$$3 \le n \le 10^5$$$) — количество вершин в торте.</p><p>Далее следуют $$$n - 2$$$ строк, описывающих номера вершин кусков торта: каждая строка состоит из трех различных целых чисел $$$a, b, c$$$ ($$$1 \le a, b, c \le n$$$) — номера вершин куска торта, записанные в произвольном порядке. Сами куски тоже заданы в произвольном порядке.</p><p>Гарантируется, что ответ на каждый из тестов существует. Также гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$2t$$$ строк — ответы на заданные $$$t$$$ наборов в порядке их записи во входных данных. Каждый ответ должен состоять из $$$2$$$ строк.</p><p>В первой строке ответа на набор входных данных выведите $$$n$$$ различных чисел $$$p_1, p_2, \dots, p_n$$$($$$1 \le p_i \le n$$$) — номера вершин торта в порядке по или против часовой стрелки. Просмотр вершин торта можно начать с любой из них.</p><p>Во второй строке ответа на набор входных данных выведите $$$n - 2$$$ различных чисел $$$q_1, q_2, \dots, q_{n - 2}$$$($$$1 \le q_i \le n - 2$$$) — порядок отрезания кусков торта. Номер куска торта соответствует его номеру во входных данных.</p><p>Если существует несколько ответов, выведите любой. Гарантируется, что ответ на каждый из тестов существует.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 6 3 6 5 5 2 4 5 4 6 6 3 1 6 2 5 6 2 5 1 4 1 2 1 3 5 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 6 4 2 5 3 4 2 3 1 1 4 2 6 5 3 3 4 2 1 1 3 2 1 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="043f9c0f18b83873abfc8c9c987132e0"/> <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="ffd47bcd882b82e4d7d9030ecf8ffd9ed6eeaa55"/> <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='043f9c0f18b83873abfc8c9c987132e0'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1282%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='043f9c0f18b83873abfc8c9c987132e0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1282">Codeforces Round 610 (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='043f9c0f18b83873abfc8c9c987132e0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1282/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='043f9c0f18b83873abfc8c9c987132e0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="502550"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='043f9c0f18b83873abfc8c9c987132e0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="502550"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72408" title="Codeforces Round #610 (Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10156:10157" 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/72461?locale=ru" title="72461" target="_blank">72461 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10167" resourceName="72461" resourceManual="true" src="//codeforces.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/72461?locale=en" title="72461" target="_blank">72461 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10166" resourceName="72461" resourceManual="true" src="//codeforces.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/1282">Задачи</a></li> <li><a href="/contest/1282/submit">Отослать</a></li> <li><a href="/contest/1282/my">Мои посылки</a></li> <li><a href="/contest/1282/status">Статус</a></li> <li><a href="/contest/1282/hacks">Взломы</a></li> <li><a href="/contest/1282/room/1">Комната</a></li> <li><a href="/contest/1282/standings">Положение</a></li> <li><a href="/contest/1282/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_79f3d280a68d3cca9bb6ef922e86001901d300bd"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Тортик - ложь</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Мы заботимся о моральном состоянии участников соревнования. Поэтому вместо задачи мы предлагаем вам полакомиться кусочком торта.</span></p><p><span class="tex-font-style-it">Ох, кто-то уже разрезал торт! Мы просили их дождаться вас, но они не послушали. Если поторопитесь, успеете взять кусочек. Вы, конечно, перед тем, как попробовать торт, задумались, как торт был разрезан.</span></p><p>Известно, что торт изначально представлял собой правильный $$$n$$$-угольник, каждая вершина которого имела уникальный номер от $$$1$$$ до $$$n$$$. Вершины были пронумерованы в некотором произвольном порядке.</p><p>Каждый кусок торта — это треугольник. Торт разрезали на $$$n - 2$$$ куска следующим образом: каждый раз проводили один разрез ножом (от вершины до вершины) такой, что от текущего торта отделялся ровно один треугольный кусок, а оставшаяся часть продолжала составлять выпуклый многоугольник. Иными словами, каждый раз выбирали три подряд идущие вершины многоугольника и отрезали соответствующий треугольник.</p><p>Возможный процесс разрезания торта представлен на рисунке ниже.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6bf414b22f71f67fe022c91f039ead6674986c6c.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Пример разрезания 6-угольного торта.</span> </center><p>Вам задан набор получившихся $$$n-2$$$ треугольных кусочков в произвольном порядке. Вершины каждого из кусочков записаны в произвольном порядке — по или против часовой стрелки. Каждый кусочек задается тремя числами — номерами соответствующих ему вершин $$$n$$$-угольного торта.</p><p>Например, для ситуации с рисунком выше вам мог быть задан набор кусочков: $$$[3, 6, 5], [5, 2, 4], [5, 4, 6], [6, 3, 1]$$$.</p><p>Вас интересуют два вопроса.</p><ul> <li> Какая была нумерация вершин $$$n$$$-угольного торта? </li><li> В каком порядке отрезались кусочки? </li></ul><p>Формально, вам предстоит найти две перестановки $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) и $$$q_1, q_2, \dots, q_{n - 2}$$$ ($$$1 \le q_i \le n - 2$$$) такие, что если вершины торта пронумерованы числами $$$p_1, p_2, \dots, p_n$$$ в порядке по или против часовой стрелки, то при отрезании кусков торта в порядке $$$q_1, q_2, \dots, q_{n - 2}$$$ всегда отрезается треугольный кусок так, что оставшаяся часть образует один выпуклый многоугольник.</p><p>Например, для рисунка выше искомыми перестановками могли бы быть: $$$p=[2, 4, 6, 1, 3, 5]$$$ (или любой её циклический сдвиг, или её переворот и после этого любой циклический сдвиг) и $$$q=[2, 4, 1, 3]$$$.</p><p>Напишите программу, которая по заданным треугольным кусочкам находит любую подходящую пару перестановок $$$p$$$ и $$$q$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных. Далее следуют $$$t$$$ независимых наборов входных данных.</p><p>Первая строка каждого набора состоит из одного целого числа $$$n$$$ ($$$3 \le n \le 10^5$$$) — количество вершин в торте.</p><p>Далее следуют $$$n - 2$$$ строк, описывающих номера вершин кусков торта: каждая строка состоит из трех различных целых чисел $$$a, b, c$$$ ($$$1 \le a, b, c \le n$$$) — номера вершин куска торта, записанные в произвольном порядке. Сами куски тоже заданы в произвольном порядке.</p><p>Гарантируется, что ответ на каждый из тестов существует. Также гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$2t$$$ строк — ответы на заданные $$$t$$$ наборов в порядке их записи во входных данных. Каждый ответ должен состоять из $$$2$$$ строк.</p><p>В первой строке ответа на набор входных данных выведите $$$n$$$ различных чисел $$$p_1, p_2, \dots, p_n$$$($$$1 \le p_i \le n$$$) — номера вершин торта в порядке по или против часовой стрелки. Просмотр вершин торта можно начать с любой из них.</p><p>Во второй строке ответа на набор входных данных выведите $$$n - 2$$$ различных чисел $$$q_1, q_2, \dots, q_{n - 2}$$$($$$1 \le q_i \le n - 2$$$) — порядок отрезания кусков торта. Номер куска торта соответствует его номеру во входных данных.</p><p>Если существует несколько ответов, выведите любой. Гарантируется, что ответ на каждый из тестов существует.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 6 3 6 5 5 2 4 5 4 6 6 3 1 6 2 5 6 2 5 1 4 1 2 1 3 5 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 6 4 2 5 3 4 2 3 1 1 4 2 6 5 3 3 4 2 1 1 3 2 1 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:53: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:'812492bcf8fa16db',t:'MTY5NjY2NTIzNi4xMzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2400"]
1283A
1283
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>Новый год уже на подходе и вы настолько взволнованы, что хотите узнать, сколько минут до него осталось. Вы знаете, что сейчас часы показывают время «$$$h$$$ часов, $$$m$$$ минут», где $$$0 \le hh &lt; 24$$$ и $$$0 \le mm &lt; 60$$$.</p><p>Ваша задача — найти количество минут до Нового года! Вы знаете, что Новый год наступит, когда часы покажут $$$0$$$ часов и $$$0$$$ минут.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 1439$$$) — количество наборов входных данных.</p><p>Следующие $$$t$$$ строк содержат наборы входных данных: $$$i$$$-я строка содержит время в виде двух целых чисел $$$h$$$ и $$$m$$$ ($$$0 \le h &lt; 24$$$, $$$0 \le m &lt; 60$$$). Гарантируется, что это время <span class="tex-font-style-bf">не равно</span> полуночи, то есть одновременно не могут выполняться два условия $$$h=0$$$ и $$$m=0$$$. Гарантируется, что $$$h$$$ и $$$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> 5 23 55 23 0 0 1 4 20 23 59 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 60 1439 1180 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ответ на первый набор входных данных:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/658924f6324978d956921e49b38e5fa3bcecbd2b.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="28585ff49a6e018ddca55a4c8ef8460b"/> <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="8f849505202bf1d57883c5e8122e8e4e16e9cdc0"/> <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='28585ff49a6e018ddca55a4c8ef8460b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1283%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='28585ff49a6e018ddca55a4c8ef8460b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1283">Codeforces Round 611 (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='28585ff49a6e018ddca55a4c8ef8460b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1283/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='28585ff49a6e018ddca55a4c8ef8460b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="504967"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='28585ff49a6e018ddca55a4c8ef8460b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="504967"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72541" title="Codeforces Round #611 (Div. 3)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10197" resourceName="Codeforces Round #611 (Div. 3)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/72592" title="Разбор Codeforces Round #611 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10605:10606" 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/1283">Задачи</a></li> <li><a href="/contest/1283/submit">Отослать</a></li> <li><a href="/contest/1283/my">Мои посылки</a></li> <li><a href="/contest/1283/status">Статус</a></li> <li><a href="/contest/1283/hacks">Взломы</a></li> <li><a href="/contest/1283/standings">Положение</a></li> <li><a href="/contest/1283/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_70e6b4f27b228cdc4ba2bcfea4dcf00592e4c3c8"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Новый год уже на подходе и вы настолько взволнованы, что хотите узнать, сколько минут до него осталось. Вы знаете, что сейчас часы показывают время «$$$h$$$ часов, $$$m$$$ минут», где $$$0 \le hh &lt; 24$$$ и $$$0 \le mm &lt; 60$$$.</p><p>Ваша задача — найти количество минут до Нового года! Вы знаете, что Новый год наступит, когда часы покажут $$$0$$$ часов и $$$0$$$ минут.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 1439$$$) — количество наборов входных данных.</p><p>Следующие $$$t$$$ строк содержат наборы входных данных: $$$i$$$-я строка содержит время в виде двух целых чисел $$$h$$$ и $$$m$$$ ($$$0 \le h &lt; 24$$$, $$$0 \le m &lt; 60$$$). Гарантируется, что это время <span class="tex-font-style-bf">не равно</span> полуночи, то есть одновременно не могут выполняться два условия $$$h=0$$$ и $$$m=0$$$. Гарантируется, что $$$h$$$ и $$$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> 5 23 55 23 0 0 1 4 20 23 59 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 60 1439 1180 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ответ на первый набор входных данных:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/658924f6324978d956921e49b38e5fa3bcecbd2b.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:53: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:'812492c58a089d70',t:'MTY5NjY2NTIzOC4zNDYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1283B
1283
B
ru
B. Разделение конфет
<div class="problem-statement"><div class="header"><div class="title">B. Разделение конфет</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Деда Мороза есть $$$n$$$ конфет и он хочет подарить их $$$k$$$ детям. Он хочет разделить как можно больше конфет среди всех $$$k$$$ детей. Санта не может разделять одну конфету на части, но он может не использовать некоторые конфеты вообще.</p><p>Пусть ребенок, который получил минимальное количество конфет, получил ровно $$$a$$$ конфет, а ребенок, который получил максимальное количество конфет, получил $$$b$$$ конфет. Тогда Дед Мороз будет <span class="tex-font-style-bf">доволен</span>, если оба следующих условия выполняются одновременно:</p><ul> <li> $$$b - a \le 1$$$ (это значит, что $$$b = a$$$ или $$$b = a + 1$$$); </li><li> количество детей, кто имеет $$$a+1$$$ конфету (<span class="tex-font-style-bf">заметьте, что $$$a+1$$$ не обязательно равно $$$b$$$</span>) не превосходит $$$\lfloor\frac{k}{2}\rfloor$$$ (меньше либо равно $$$\lfloor\frac{k}{2}\rfloor$$$). </li></ul><p>Запись $$$\lfloor\frac{k}{2}\rfloor$$$ означает $$$k$$$ делённое на $$$2$$$ и округлённое <span class="tex-font-style-bf">вниз</span> до ближайшего целого числа. Например, если $$$k=5$$$, то $$$\lfloor\frac{k}{2}\rfloor=\lfloor\frac{5}{2}\rfloor=2$$$.</p><p>Ваша задача — найти максимальное количество конфет, которые Дед Мороз сможет дать детям таким образом, чтобы он был <span class="tex-font-style-bf">доволен</span>.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — количество наборов входных данных.</p><p>Следующие $$$t$$$ строк описывают наборы входных данных. $$$i$$$-й набор входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 10^9$$$) — количество конфет и количество детей.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ на каждый набор входных данных — максимальное количество конфет, которые Дед Мороз сможет дать детям таким образом, чтобы он был <span class="tex-font-style-bf">доволен</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 2 19 4 12 7 6 2 100000 50010 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 18 10 6 75015 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Дед Мороз может дать $$$3$$$ и $$$2$$$ конфеты детям. Здесь $$$a=2, b=3,a+1=3$$$.</p><p>Во втором наборе входных данных Дед Мороз может дать $$$5, 5, 4$$$ и $$$4$$$ конфеты. Здесь $$$a=4,b=5,a+1=5$$$. Ответ не может быть больше, потому что тогда количество детей с $$$5$$$ конфетами будет равно $$$3$$$.</p><p>В третьем наборе входных данных Дед Мороз может распределить конфеты следующим образом: $$$[1, 2, 2, 1, 1, 2, 1]$$$. Здесь $$$a=1,b=2,a+1=2$$$. Он не может распределить две оставшиеся конфеты таким образом, чтобы он остался доволен.</p><p>В четвертом наборе входных данных Дед Мороз может распределить конфеты следующим образом: $$$[3, 3]$$$. Здесь $$$a=3, b=3, a+1=4$$$. Дед Мороз распределил все $$$6$$$ конфет.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="2ba4c227b0b408aba8f359e17c26f764"/> <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="8f849505202bf1d57883c5e8122e8e4e16e9cdc0"/> <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='2ba4c227b0b408aba8f359e17c26f764'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1283%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='2ba4c227b0b408aba8f359e17c26f764'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1283">Codeforces Round 611 (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='2ba4c227b0b408aba8f359e17c26f764'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1283/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='2ba4c227b0b408aba8f359e17c26f764'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="504968"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2ba4c227b0b408aba8f359e17c26f764'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="504968"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72541" title="Codeforces Round #611 (Div. 3)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10197" resourceName="Codeforces Round #611 (Div. 3)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/72592" title="Разбор Codeforces Round #611 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10605:10606" 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/1283">Задачи</a></li> <li><a href="/contest/1283/submit">Отослать</a></li> <li><a href="/contest/1283/my">Мои посылки</a></li> <li><a href="/contest/1283/status">Статус</a></li> <li><a href="/contest/1283/hacks">Взломы</a></li> <li><a href="/contest/1283/standings">Положение</a></li> <li><a href="/contest/1283/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_799c4d676b5385a3da217796b64f59b1642962b1"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Разделение конфет</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Деда Мороза есть $$$n$$$ конфет и он хочет подарить их $$$k$$$ детям. Он хочет разделить как можно больше конфет среди всех $$$k$$$ детей. Санта не может разделять одну конфету на части, но он может не использовать некоторые конфеты вообще.</p><p>Пусть ребенок, который получил минимальное количество конфет, получил ровно $$$a$$$ конфет, а ребенок, который получил максимальное количество конфет, получил $$$b$$$ конфет. Тогда Дед Мороз будет <span class="tex-font-style-bf">доволен</span>, если оба следующих условия выполняются одновременно:</p><ul> <li> $$$b - a \le 1$$$ (это значит, что $$$b = a$$$ или $$$b = a + 1$$$); </li><li> количество детей, кто имеет $$$a+1$$$ конфету (<span class="tex-font-style-bf">заметьте, что $$$a+1$$$ не обязательно равно $$$b$$$</span>) не превосходит $$$\lfloor\frac{k}{2}\rfloor$$$ (меньше либо равно $$$\lfloor\frac{k}{2}\rfloor$$$). </li></ul><p>Запись $$$\lfloor\frac{k}{2}\rfloor$$$ означает $$$k$$$ делённое на $$$2$$$ и округлённое <span class="tex-font-style-bf">вниз</span> до ближайшего целого числа. Например, если $$$k=5$$$, то $$$\lfloor\frac{k}{2}\rfloor=\lfloor\frac{5}{2}\rfloor=2$$$.</p><p>Ваша задача — найти максимальное количество конфет, которые Дед Мороз сможет дать детям таким образом, чтобы он был <span class="tex-font-style-bf">доволен</span>.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — количество наборов входных данных.</p><p>Следующие $$$t$$$ строк описывают наборы входных данных. $$$i$$$-й набор входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 10^9$$$) — количество конфет и количество детей.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ на каждый набор входных данных — максимальное количество конфет, которые Дед Мороз сможет дать детям таким образом, чтобы он был <span class="tex-font-style-bf">доволен</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 2 19 4 12 7 6 2 100000 50010 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 18 10 6 75015 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Дед Мороз может дать $$$3$$$ и $$$2$$$ конфеты детям. Здесь $$$a=2, b=3,a+1=3$$$.</p><p>Во втором наборе входных данных Дед Мороз может дать $$$5, 5, 4$$$ и $$$4$$$ конфеты. Здесь $$$a=4,b=5,a+1=5$$$. Ответ не может быть больше, потому что тогда количество детей с $$$5$$$ конфетами будет равно $$$3$$$.</p><p>В третьем наборе входных данных Дед Мороз может распределить конфеты следующим образом: $$$[1, 2, 2, 1, 1, 2, 1]$$$. Здесь $$$a=1,b=2,a+1=2$$$. Он не может распределить две оставшиеся конфеты таким образом, чтобы он остался доволен.</p><p>В четвертом наборе входных данных Дед Мороз может распределить конфеты следующим образом: $$$[3, 3]$$$. Здесь $$$a=3, b=3, a+1=4$$$. Дед Мороз распределил все $$$6$$$ конфет.</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:53: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:'812492d35aff9d9c',t:'MTY5NjY2NTIzOS42NzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1283C
1283
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$$$ друзей хотят подарить друг другу подарки на Новый год. Каждый друг должен подарить <span class="tex-font-style-bf">ровно</span> один подарок и получить <span class="tex-font-style-bf">ровно</span> один подарок. Друг <span class="tex-font-style-bf">не может</span> подарить подарок самому себе.</p><p>Для каждого друга известно значение $$$f_i$$$: оно или равно $$$f_i = 0$$$, если $$$i$$$-й друг не знает, кому он хочет подарить подарок, или равно $$$1 \le f_i \le n$$$, если $$$i$$$-й друг хочет подарить подарок другу $$$f_i$$$.</p><p>Вы хотите заполнить неизвестные значения ($$$f_i = 0$$$) таким образом, чтобы каждый друг подарил <span class="tex-font-style-bf">ровно</span> один подарок и получил <span class="tex-font-style-bf">ровно</span> один подарок, а также <span class="tex-font-style-bf">не было</span> друга, который дарит подарок сам себе. Гарантируется, что изначальная информация не противоречива.</p><p>Если существует несколько возможных ответов, выведите любой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — количество друзей.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$f_1, f_2, \dots, f_n$$$ ($$$0 \le f_i \le n$$$, $$$f_i \ne i$$$, все $$$f_i \ne 0$$$ различны), где $$$f_i$$$ или равно $$$f_i = 0$$$, если $$$i$$$-й друг не знает, кому он хочет подарить подарок, или равно $$$1 \le f_i \le n$$$, если $$$i$$$-й друг хочет подарить подарок другу $$$f_i$$$. Также гарантируется, что есть <span class="tex-font-style-bf">хотя бы два</span> значения $$$f_i = 0$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел $$$nf_1, nf_2, \dots, nf_n$$$, где $$$nf_i$$$ должно быть равно $$$f_i$$$, если $$$f_i \ne 0$$$, или номеру друга, которому $$$i$$$-й друг хочет подарить подарок. Все значения $$$nf_i$$$ должны быть различны, $$$nf_i$$$ не может быть равно $$$i$$$. Каждый друг должен подарить <span class="tex-font-style-bf">ровно</span> один подарок и получить <span class="tex-font-style-bf">ровно</span> один подарок, а также <span class="tex-font-style-bf">не должно быть</span> друга, который дарит подарок сам себе.</p><p>Если существует несколько возможных ответов, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 0 0 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 3 1 2 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 7 0 0 1 4 0 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 3 2 1 4 5 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 7 4 0 3 0 5 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 4 2 3 6 5 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 1 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 4 5 3 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="4f424b630048613fd95e1925a3116fde"/> <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="8f849505202bf1d57883c5e8122e8e4e16e9cdc0"/> <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='4f424b630048613fd95e1925a3116fde'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1283%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='4f424b630048613fd95e1925a3116fde'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1283">Codeforces Round 611 (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='4f424b630048613fd95e1925a3116fde'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1283/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='4f424b630048613fd95e1925a3116fde'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="504969"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4f424b630048613fd95e1925a3116fde'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="504969"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72541" title="Codeforces Round #611 (Div. 3)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10197" resourceName="Codeforces Round #611 (Div. 3)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/72592" title="Разбор Codeforces Round #611 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10605:10606" 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/1283">Задачи</a></li> <li><a href="/contest/1283/submit">Отослать</a></li> <li><a href="/contest/1283/my">Мои посылки</a></li> <li><a href="/contest/1283/status">Статус</a></li> <li><a href="/contest/1283/hacks">Взломы</a></li> <li><a href="/contest/1283/standings">Положение</a></li> <li><a href="/contest/1283/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ffabc1f788d19ac38f4033030f5e8565d2679b55"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ друзей хотят подарить друг другу подарки на Новый год. Каждый друг должен подарить <span class="tex-font-style-bf">ровно</span> один подарок и получить <span class="tex-font-style-bf">ровно</span> один подарок. Друг <span class="tex-font-style-bf">не может</span> подарить подарок самому себе.</p><p>Для каждого друга известно значение $$$f_i$$$: оно или равно $$$f_i = 0$$$, если $$$i$$$-й друг не знает, кому он хочет подарить подарок, или равно $$$1 \le f_i \le n$$$, если $$$i$$$-й друг хочет подарить подарок другу $$$f_i$$$.</p><p>Вы хотите заполнить неизвестные значения ($$$f_i = 0$$$) таким образом, чтобы каждый друг подарил <span class="tex-font-style-bf">ровно</span> один подарок и получил <span class="tex-font-style-bf">ровно</span> один подарок, а также <span class="tex-font-style-bf">не было</span> друга, который дарит подарок сам себе. Гарантируется, что изначальная информация не противоречива.</p><p>Если существует несколько возможных ответов, выведите любой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — количество друзей.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$f_1, f_2, \dots, f_n$$$ ($$$0 \le f_i \le n$$$, $$$f_i \ne i$$$, все $$$f_i \ne 0$$$ различны), где $$$f_i$$$ или равно $$$f_i = 0$$$, если $$$i$$$-й друг не знает, кому он хочет подарить подарок, или равно $$$1 \le f_i \le n$$$, если $$$i$$$-й друг хочет подарить подарок другу $$$f_i$$$. Также гарантируется, что есть <span class="tex-font-style-bf">хотя бы два</span> значения $$$f_i = 0$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел $$$nf_1, nf_2, \dots, nf_n$$$, где $$$nf_i$$$ должно быть равно $$$f_i$$$, если $$$f_i \ne 0$$$, или номеру друга, которому $$$i$$$-й друг хочет подарить подарок. Все значения $$$nf_i$$$ должны быть различны, $$$nf_i$$$ не может быть равно $$$i$$$. Каждый друг должен подарить <span class="tex-font-style-bf">ровно</span> один подарок и получить <span class="tex-font-style-bf">ровно</span> один подарок, а также <span class="tex-font-style-bf">не должно быть</span> друга, который дарит подарок сам себе.</p><p>Если существует несколько возможных ответов, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 0 0 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 3 1 2 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 7 0 0 1 4 0 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 3 2 1 4 5 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 7 4 0 3 0 5 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 4 2 3 6 5 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 1 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 4 5 3 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'812492dbaff70022',t:'MTY5NjY2NTI0MS4wMDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1500"]
1283D
1283
D
ru
D. Рождественские деревья
<div class="problem-statement"><div class="header"><div class="title">D. Рождественские деревья</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На бесконечной числовой прямой находятся $$$n$$$ рождественных деревьев. $$$i$$$-е дерево растет на позиции $$$x_i$$$. Гарантируется, что все значения $$$x_i$$$ различны.</p><p>Каждая <span class="tex-font-style-bf">целочисленная</span> точка может быть либо занята рождественским деревом, либо занята человеком, либо не занята вообще. Нецелые точки не могут быть заняты ничем.</p><p>Есть $$$m$$$ человек, которые хотят отпраздновать Рождество. Пусть $$$y_1, y_2, \dots, y_m$$$ — это позиции людей (заметьте, что все значения $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ должны быть <span class="tex-font-style-bf">различны</span> и все $$$y_j$$$ должны быть <span class="tex-font-style-bf">целыми</span>). Вы хотите найти такое расположение людей, что значение $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ минимально возможное (другими словами, сумма расстояний до ближайшего рождественского дерева по всем людям должна быть минимизирована).</p><p>Другими словами, пусть $$$d_j$$$ равно дистанции от $$$j$$$-го человека до ближайшего к нему рождественского дерева ($$$d_j = \min\limits_{i=1}^{n} |y_j - x_i|$$$). Тогда вам надо выбрать такие позиции $$$y_1, y_2, \dots, y_m$$$, что $$$\sum\limits_{j=1}^{m} d_j$$$ минимально возможна.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — количество рождественских деревьев и количество людей.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$), где $$$x_i$$$ равно позиции $$$i$$$-го рождественского дерева. Гарантируется, что все $$$x_i$$$ различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите одно целое число $$$res$$$ — минимально возможное значение $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ (другими словами, сумму расстояний до ближайшего рождественского дерева по всем людям).</p><p>Во второй строке выведите $$$m$$$ целых чисел $$$y_1, y_2, \dots, y_m$$$ ($$$-2 \cdot 10^9 \le y_j \le 2 \cdot 10^9$$$), где $$$y_j$$$ равно позиции $$$j$$$-го человека. Все $$$y_j$$$ должны быть различными, а еще все значения $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ должны быть <span class="tex-font-style-bf">различными</span>.</p><p>Если существует несколько ответов, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 6 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 -1 2 6 4 0 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 0 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 5 -2 4 -1 2 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="1bd539344a3e6b47718919fd98a62307"/> <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="8f849505202bf1d57883c5e8122e8e4e16e9cdc0"/> <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='1bd539344a3e6b47718919fd98a62307'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1283%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='1bd539344a3e6b47718919fd98a62307'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1283">Codeforces Round 611 (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='1bd539344a3e6b47718919fd98a62307'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1283/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах"> кратчайшие пути </span> </div> <div class="roundbox borderTopRound 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='1bd539344a3e6b47718919fd98a62307'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="504970"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1bd539344a3e6b47718919fd98a62307'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="504970"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72541" title="Codeforces Round #611 (Div. 3)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10197" resourceName="Codeforces Round #611 (Div. 3)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/72592" title="Разбор Codeforces Round #611 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10605:10606" 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/1283">Задачи</a></li> <li><a href="/contest/1283/submit">Отослать</a></li> <li><a href="/contest/1283/my">Мои посылки</a></li> <li><a href="/contest/1283/status">Статус</a></li> <li><a href="/contest/1283/hacks">Взломы</a></li> <li><a href="/contest/1283/standings">Положение</a></li> <li><a href="/contest/1283/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d0c8dc463f3000a2e79b26873c647eb412940f74"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Рождественские деревья</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На бесконечной числовой прямой находятся $$$n$$$ рождественных деревьев. $$$i$$$-е дерево растет на позиции $$$x_i$$$. Гарантируется, что все значения $$$x_i$$$ различны.</p><p>Каждая <span class="tex-font-style-bf">целочисленная</span> точка может быть либо занята рождественским деревом, либо занята человеком, либо не занята вообще. Нецелые точки не могут быть заняты ничем.</p><p>Есть $$$m$$$ человек, которые хотят отпраздновать Рождество. Пусть $$$y_1, y_2, \dots, y_m$$$ — это позиции людей (заметьте, что все значения $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ должны быть <span class="tex-font-style-bf">различны</span> и все $$$y_j$$$ должны быть <span class="tex-font-style-bf">целыми</span>). Вы хотите найти такое расположение людей, что значение $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ минимально возможное (другими словами, сумма расстояний до ближайшего рождественского дерева по всем людям должна быть минимизирована).</p><p>Другими словами, пусть $$$d_j$$$ равно дистанции от $$$j$$$-го человека до ближайшего к нему рождественского дерева ($$$d_j = \min\limits_{i=1}^{n} |y_j - x_i|$$$). Тогда вам надо выбрать такие позиции $$$y_1, y_2, \dots, y_m$$$, что $$$\sum\limits_{j=1}^{m} d_j$$$ минимально возможна.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — количество рождественских деревьев и количество людей.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$), где $$$x_i$$$ равно позиции $$$i$$$-го рождественского дерева. Гарантируется, что все $$$x_i$$$ различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите одно целое число $$$res$$$ — минимально возможное значение $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ (другими словами, сумму расстояний до ближайшего рождественского дерева по всем людям).</p><p>Во второй строке выведите $$$m$$$ целых чисел $$$y_1, y_2, \dots, y_m$$$ ($$$-2 \cdot 10^9 \le y_j \le 2 \cdot 10^9$$$), где $$$y_j$$$ равно позиции $$$j$$$-го человека. Все $$$y_j$$$ должны быть различными, а еще все значения $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ должны быть <span class="tex-font-style-bf">различными</span>.</p><p>Если существует несколько ответов, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 6 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 -1 2 6 4 0 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 0 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 5 -2 4 -1 2 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'812492e40f7916b3',t:'MTY5NjY2NTI0Mi40NjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "*1800"]
1283E
1283
E
ru
E. Новогодние посиделки
<div class="problem-statement"><div class="header"><div class="title">E. Новогодние посиделки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>О, Новый год. Лучшее время, чтобы собрать всех друзей вместе и окунуться в теплые воспоминания прошедшего года...</p><p>$$$n$$$ друзей живут в городе, который можно представить в виде числовой прямой. $$$i$$$-й друг живет в городе с координатой $$$x_i$$$. $$$i$$$-й друг может пойти отмечать Новый год в дом с координатой $$$x_i-1$$$, $$$x_i+1$$$ или остаться у себя в $$$x_i$$$. Каждый друг может пойти куда-либо не более одного раза.</p><p>Для всех друзей выполняется $$$1 \le x_i \le n$$$, но они могут ходить и в дома с координатами $$$0$$$ и $$$n+1$$$ (если координаты их домов $$$1$$$ или $$$n$$$, соответственно).</p><p>Например, пусть начальные позиции будут $$$x = [1, 2, 4, 4]$$$. Тогда конечные позиции могут быть $$$[1, 3, 3, 4]$$$, $$$[0, 2, 3, 3]$$$, $$$[2, 2, 5, 5]$$$, $$$[2, 1, 3, 5]$$$ и так далее. Количество заполненных домов — это количество различных позиций среди конечных.</p><p>Теперь все друзья выбрали, куда пойти. После всех перемещений подсчитали количество заполненных домов. Какое минимальное и максимальное количество заполненных домов могло получиться?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество друзей.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le n$$$) — координаты домов друзей.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа — минимальное и максимальное количество заполненных домов, которые могли получиться после всех перемещений.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 9 1 1 8 8 8 4 4 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 4 3 7 1 4 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере друзья могут пойти в $$$[2, 2, 3, 3]$$$. То есть друг $$$1$$$ идет в $$$x_1+1$$$, друг $$$2$$$ остается у себя дома в $$$x_2$$$, друг $$$3$$$ идет в $$$x_3-1$$$ и друг $$$4$$$ идет в $$$x_4-1$$$. $$$[1, 1, 3, 3]$$$, $$$[2, 2, 3, 3]$$$ или $$$[2, 2, 4, 4]$$$ также являются возможными способами получить $$$2$$$ заполненных дома.</p><p>Для максимального количества заполненных домов друзья могут пойти в $$$[1, 2, 3, 4]$$$ или в $$$[0, 2, 4, 5]$$$, например.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="e0990f8e1ce9f5a87fe964818c12efe9"/> <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="8f849505202bf1d57883c5e8122e8e4e16e9cdc0"/> <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='e0990f8e1ce9f5a87fe964818c12efe9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1283%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='e0990f8e1ce9f5a87fe964818c12efe9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1283">Codeforces Round 611 (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='e0990f8e1ce9f5a87fe964818c12efe9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1283/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='e0990f8e1ce9f5a87fe964818c12efe9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="504971"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e0990f8e1ce9f5a87fe964818c12efe9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="504971"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72541" title="Codeforces Round #611 (Div. 3)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10197" resourceName="Codeforces Round #611 (Div. 3)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/72592" title="Разбор Codeforces Round #611 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10605:10606" 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/1283">Задачи</a></li> <li><a href="/contest/1283/submit">Отослать</a></li> <li><a href="/contest/1283/my">Мои посылки</a></li> <li><a href="/contest/1283/status">Статус</a></li> <li><a href="/contest/1283/hacks">Взломы</a></li> <li><a href="/contest/1283/standings">Положение</a></li> <li><a href="/contest/1283/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_067aa39e570de5b353df30a7684306d1fab56372"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Новогодние посиделки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>О, Новый год. Лучшее время, чтобы собрать всех друзей вместе и окунуться в теплые воспоминания прошедшего года...</p><p>$$$n$$$ друзей живут в городе, который можно представить в виде числовой прямой. $$$i$$$-й друг живет в городе с координатой $$$x_i$$$. $$$i$$$-й друг может пойти отмечать Новый год в дом с координатой $$$x_i-1$$$, $$$x_i+1$$$ или остаться у себя в $$$x_i$$$. Каждый друг может пойти куда-либо не более одного раза.</p><p>Для всех друзей выполняется $$$1 \le x_i \le n$$$, но они могут ходить и в дома с координатами $$$0$$$ и $$$n+1$$$ (если координаты их домов $$$1$$$ или $$$n$$$, соответственно).</p><p>Например, пусть начальные позиции будут $$$x = [1, 2, 4, 4]$$$. Тогда конечные позиции могут быть $$$[1, 3, 3, 4]$$$, $$$[0, 2, 3, 3]$$$, $$$[2, 2, 5, 5]$$$, $$$[2, 1, 3, 5]$$$ и так далее. Количество заполненных домов — это количество различных позиций среди конечных.</p><p>Теперь все друзья выбрали, куда пойти. После всех перемещений подсчитали количество заполненных домов. Какое минимальное и максимальное количество заполненных домов могло получиться?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество друзей.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le n$$$) — координаты домов друзей.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа — минимальное и максимальное количество заполненных домов, которые могли получиться после всех перемещений.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 9 1 1 8 8 8 4 4 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 4 3 7 1 4 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере друзья могут пойти в $$$[2, 2, 3, 3]$$$. То есть друг $$$1$$$ идет в $$$x_1+1$$$, друг $$$2$$$ остается у себя дома в $$$x_2$$$, друг $$$3$$$ идет в $$$x_3-1$$$ и друг $$$4$$$ идет в $$$x_4-1$$$. $$$[1, 1, 3, 3]$$$, $$$[2, 2, 3, 3]$$$ или $$$[2, 2, 4, 4]$$$ также являются возможными способами получить $$$2$$$ заполненных дома.</p><p>Для максимального количества заполненных домов друзья могут пойти в $$$[1, 2, 3, 4]$$$ или в $$$[0, 2, 4, 5]$$$, например.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'812492ed0b5916f7',t:'MTY5NjY2NTI0My44MDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*1800"]
1283F
1283
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>Поликарп решил украсить свою комнату перед Новым Годом. Одно из главных украшений — гирлянда, которую он спаяет сам.</p><p>Простые гирлянды, в которых несколько лампочек расположены в ряд и соединены одним проводом, слишком скучны для Поликарпа. Он собирается спаять разветвленную гирлянду из $$$n$$$ лампочек и $$$n - 1$$$ провода. Ровно одна лампочка будет подключена к розетке, и от нее по проводам будет передаваться электроэнергия ко всем остальным лампочкам. Каждый провод соединяет ровно две лампочки, причем та из них, от которой будет идти энергия по этому проводу, называется <span class="tex-font-style-bf">главной</span>, а та, которая получает энергию по этому проводу, называется <span class="tex-font-style-bf">побочной</span>. Очевидно, для каждой лампочки существует не более одного провода, для которого она является побочной.</p><p>У каждой лампочки есть своя яркость, причем яркость $$$i$$$-й лампочки равна $$$2^i$$$. Назовем важностью провода суммарную яркость тех лампочек, которые окажутся отсоединены от источника энергии, если этот провод (и только его) удалить. Естественно, более важные провода должны быть более надежными.</p><p>Поликарп нарисовал схему гирлянды, которую он хочет спаять (на схеме указаны все $$$n$$$ лампочек и $$$n - 1$$$ проводов, а также отмечена лампочка, которая будет подключена к электросети; провода расположены так, что энергия может передаваться до всех лампочек). После этого Поликарп посчитал важность каждого провода, пронумеровал их от $$$1$$$ до $$$n - 1$$$ в порядке уменьшения важности, а затем (с учётом новой нумерации проводов) для каждого провода записал номер его главной лампочки.</p><p>На следующий день Поликарп купил необходимые провода и решил спаять гирлянду — но, к сожалению, не смог найти схему. Вспомнив, что у него есть список номеров главных лампочек для всех проводов в порядке уменьшения их важности, он решил попытаться восстановить схему гирлянды по этому списку. Можете ли вы помочь ему с восстановлением схемы?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — количество лампочек.</p><p>Во второй строке заданы $$$n - 1$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n - 1}$$$ ($$$1 \le a_i \le n$$$), где $$$a_i$$$ — номер главной лампочки для $$$i$$$-го провода (провода пронумерованы в порядке уменьшения важности).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если схему восстановить невозможно, выведите одно целое число: $$$-1$$$.</p><p>В противном случае выведите схему следующим образом. В первой строке выведите одно целое число $$$k$$$ ($$$1 \le k \le n$$$) — номер лампочки, подключенной к электросети. Затем выведите $$$n - 1$$$ строк, в каждой из которых должны быть заданы два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) — номера лампочек, соединенных некоторым проводом. Описания проводов (и номера лампочек, соединенных проводом) могут быть выведены в любом порядке. Вывод должен соответствовать некоторой схеме, по которой Поликарп мог бы выписать список чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n - 1}$$$. Если таких схем несколько, выведите любую из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 3 6 3 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 3 6 5 1 3 1 4 5 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Схема для первого примера (R обозначает лампу, подключенную к сети; числа на проводах обозначают их важность):</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/58abff3d3a7c24c4953511bd48e3fa31c1cf4e67.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="b3e74568c57700d21d4adeb4882f3c58"/> <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="8f849505202bf1d57883c5e8122e8e4e16e9cdc0"/> <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='b3e74568c57700d21d4adeb4882f3c58'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1283%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='b3e74568c57700d21d4adeb4882f3c58'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1283">Codeforces Round 611 (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='b3e74568c57700d21d4adeb4882f3c58'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1283/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='b3e74568c57700d21d4adeb4882f3c58'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="504972"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b3e74568c57700d21d4adeb4882f3c58'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="504972"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72541" title="Codeforces Round #611 (Div. 3)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10197" resourceName="Codeforces Round #611 (Div. 3)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/72592" title="Разбор Codeforces Round #611 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10605:10606" 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/1283">Задачи</a></li> <li><a href="/contest/1283/submit">Отослать</a></li> <li><a href="/contest/1283/my">Мои посылки</a></li> <li><a href="/contest/1283/status">Статус</a></li> <li><a href="/contest/1283/hacks">Взломы</a></li> <li><a href="/contest/1283/standings">Положение</a></li> <li><a href="/contest/1283/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e378e1e03ca139c2a71be88a7d49c182c1926634"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Поликарп решил украсить свою комнату перед Новым Годом. Одно из главных украшений — гирлянда, которую он спаяет сам.</p><p>Простые гирлянды, в которых несколько лампочек расположены в ряд и соединены одним проводом, слишком скучны для Поликарпа. Он собирается спаять разветвленную гирлянду из $$$n$$$ лампочек и $$$n - 1$$$ провода. Ровно одна лампочка будет подключена к розетке, и от нее по проводам будет передаваться электроэнергия ко всем остальным лампочкам. Каждый провод соединяет ровно две лампочки, причем та из них, от которой будет идти энергия по этому проводу, называется <span class="tex-font-style-bf">главной</span>, а та, которая получает энергию по этому проводу, называется <span class="tex-font-style-bf">побочной</span>. Очевидно, для каждой лампочки существует не более одного провода, для которого она является побочной.</p><p>У каждой лампочки есть своя яркость, причем яркость $$$i$$$-й лампочки равна $$$2^i$$$. Назовем важностью провода суммарную яркость тех лампочек, которые окажутся отсоединены от источника энергии, если этот провод (и только его) удалить. Естественно, более важные провода должны быть более надежными.</p><p>Поликарп нарисовал схему гирлянды, которую он хочет спаять (на схеме указаны все $$$n$$$ лампочек и $$$n - 1$$$ проводов, а также отмечена лампочка, которая будет подключена к электросети; провода расположены так, что энергия может передаваться до всех лампочек). После этого Поликарп посчитал важность каждого провода, пронумеровал их от $$$1$$$ до $$$n - 1$$$ в порядке уменьшения важности, а затем (с учётом новой нумерации проводов) для каждого провода записал номер его главной лампочки.</p><p>На следующий день Поликарп купил необходимые провода и решил спаять гирлянду — но, к сожалению, не смог найти схему. Вспомнив, что у него есть список номеров главных лампочек для всех проводов в порядке уменьшения их важности, он решил попытаться восстановить схему гирлянды по этому списку. Можете ли вы помочь ему с восстановлением схемы?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — количество лампочек.</p><p>Во второй строке заданы $$$n - 1$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n - 1}$$$ ($$$1 \le a_i \le n$$$), где $$$a_i$$$ — номер главной лампочки для $$$i$$$-го провода (провода пронумерованы в порядке уменьшения важности).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если схему восстановить невозможно, выведите одно целое число: $$$-1$$$.</p><p>В противном случае выведите схему следующим образом. В первой строке выведите одно целое число $$$k$$$ ($$$1 \le k \le n$$$) — номер лампочки, подключенной к электросети. Затем выведите $$$n - 1$$$ строк, в каждой из которых должны быть заданы два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) — номера лампочек, соединенных некоторым проводом. Описания проводов (и номера лампочек, соединенных проводом) могут быть выведены в любом порядке. Вывод должен соответствовать некоторой схеме, по которой Поликарп мог бы выписать список чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n - 1}$$$. Если таких схем несколько, выведите любую из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 3 6 3 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 3 6 5 1 3 1 4 5 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Схема для первого примера (R обозначает лампу, подключенную к сети; числа на проводах обозначают их важность):</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/58abff3d3a7c24c4953511bd48e3fa31c1cf4e67.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'812492f59be81640',t:'MTY5NjY2NTI0NS4xNzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2200"]
1284A
1284
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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>С новым годом! 2020 год также известен как <span class="tex-font-style-it">год Gyeongja</span> (경자년, <span class="tex-font-style-it">gyeongja-nyeon</span>) в Корее. Откуда это имя? Кратко рассмотрим систему <span class="tex-font-style-it">Gapja</span>, которая традиционно используется в Корее для обозначения лет.</p><p>Существует две последовательности строк, $$$n$$$ строк $$$s_1, s_2, s_3, \ldots, s_{n}$$$ и $$$m$$$ строк $$$t_1, t_2, t_3, \ldots, t_{m}$$$. Эти строки состоят только из строчных букв алфавита. Среди этих строк могут быть одинаковые.</p><p>Назовем конкатенацией двух строк $$$x$$$ и $$$y$$$ такую строку, которая получится при последовательной записи сначала $$$x$$$, затем $$$y$$$ друг за другом, не меняя порядок символов в них. Например, конкатенация строк «<span class="tex-font-style-tt">code</span>» и «<span class="tex-font-style-tt">forces</span>» равна строке «<span class="tex-font-style-tt">codeforces</span>».</p><p>Год 1 начинается с конкатенации двух строк $$$s_1$$$ и $$$t_1$$$. Если год увеличивается на один, то мы берем следующую строку по порядку для каждой соответствующей последовательности. Если используемая в данный момент строка находится в конце массива, то переходим к первой строке.</p><p>Например, если $$$n = 3, m = 4, s = $$$<span class="tex-font-style-tt">{«<span class="tex-font-style-tt">a</span>», «<span class="tex-font-style-tt">b</span>», «<span class="tex-font-style-tt">c</span>»}</span>, $$$t =$$$ <span class="tex-font-style-tt">{«<span class="tex-font-style-tt">d</span>», «<span class="tex-font-style-tt">e</span>», «<span class="tex-font-style-tt">f</span>», «<span class="tex-font-style-tt">g</span>»}</span>, то строки для лет с 1 по 14 - <span class="tex-font-style-tt">{«<span class="tex-font-style-tt">ad</span>», «<span class="tex-font-style-tt">be</span>», «<span class="tex-font-style-tt">cf</span>», «<span class="tex-font-style-tt">ag</span>», «<span class="tex-font-style-tt">bd</span>», «<span class="tex-font-style-tt">ce</span>», «<span class="tex-font-style-tt">af</span>», «<span class="tex-font-style-tt">bg</span>», «<span class="tex-font-style-tt">cd</span>», «<span class="tex-font-style-tt">ae</span>», «<span class="tex-font-style-tt">bf</span>», «<span class="tex-font-style-tt">cg</span>», «<span class="tex-font-style-tt">ad</span>», «<span class="tex-font-style-tt">be</span>»}</span>. Обратите внимание, что название года может повторяться.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a0f0fe6cc031a0578f56346ce1e2c8e9368807ae.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Вам даются две последовательности строк размером $$$n$$$ и $$$m$$$, а также $$$q$$$ запросов. Для каждого запроса вам будет указан год. Можете ли вы найти имена, соответствующие данным годам, согласно системе <span class="tex-font-style-it">Gapja</span>?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n, m$$$ ($$$1 \le n, m \le 20$$$).</p><p>Следующая строка содержит $$$n$$$ строк $$$s_1, s_2, \ldots, s_{n}$$$. Каждая строка состоит только из строчных букв алфавита и разделена пробелами. Длина каждой строки не менее $$$1$$$ и не более $$$10$$$.</p><p>Следующая строка содержит $$$m$$$ строк $$$t_1, t_2, \ldots, t_{m}$$$. Каждая строка состоит только из строчных букв алфавита и разделена пробелами. Длина каждой строки не менее $$$1$$$ и не более $$$10$$$.</p><p>Среди заданных $$$n + m$$$ строк могут быть одинаковые (то есть не обязательно они все различны).</p><p>Следующая строка содержит одно целое число $$$q$$$ ($$$1 \le q \le 2\,020$$$).</p><p>В каждой из следующих $$$q$$$ строк записано целое число $$$y$$$ ($$$1 \le y \le 10^9$$$), обозначающее год, про который мы хотим узнать. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк. Для каждой строки выведите название года по описанному выше правилу.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> sinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый пример использует актуальные названия, используемые в системе <span class="tex-font-style-it">Gapja</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="8eb71d448dfb7d8c8806b4161d5cb902"/> <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="844107ee75ef6ee8a5d433a0bcfbbda150cb7f74"/> <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='8eb71d448dfb7d8c8806b4161d5cb902'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1284%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='8eb71d448dfb7d8c8806b4161d5cb902'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1284">Hello 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='8eb71d448dfb7d8c8806b4161d5cb902'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1284/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8eb71d448dfb7d8c8806b4161d5cb902'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="508362"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8eb71d448dfb7d8c8806b4161d5cb902'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="508362"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72725" title="Hello 2020" target="_blank">Hello 2020 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10228" resourceName="Hello 2020" resourceManual="true" src="//codeforces.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/72804" title="Hello 2020 Editorial" target="_blank">Hello 2020 Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10239" resourceName="Hello 2020 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/1284">Задачи</a></li> <li><a href="/contest/1284/submit">Отослать</a></li> <li><a href="/contest/1284/my">Мои посылки</a></li> <li><a href="/contest/1284/status">Статус</a></li> <li><a href="/contest/1284/hacks">Взломы</a></li> <li><a href="/contest/1284/room/1">Комната</a></li> <li><a href="/contest/1284/standings">Положение</a></li> <li><a href="/contest/1284/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c360dc15adce7d9686bbaa14824bc4ec66af2f32"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>С новым годом! 2020 год также известен как <span class="tex-font-style-it">год Gyeongja</span> (경자년, <span class="tex-font-style-it">gyeongja-nyeon</span>) в Корее. Откуда это имя? Кратко рассмотрим систему <span class="tex-font-style-it">Gapja</span>, которая традиционно используется в Корее для обозначения лет.</p><p>Существует две последовательности строк, $$$n$$$ строк $$$s_1, s_2, s_3, \ldots, s_{n}$$$ и $$$m$$$ строк $$$t_1, t_2, t_3, \ldots, t_{m}$$$. Эти строки состоят только из строчных букв алфавита. Среди этих строк могут быть одинаковые.</p><p>Назовем конкатенацией двух строк $$$x$$$ и $$$y$$$ такую строку, которая получится при последовательной записи сначала $$$x$$$, затем $$$y$$$ друг за другом, не меняя порядок символов в них. Например, конкатенация строк «<span class="tex-font-style-tt">code</span>» и «<span class="tex-font-style-tt">forces</span>» равна строке «<span class="tex-font-style-tt">codeforces</span>».</p><p>Год 1 начинается с конкатенации двух строк $$$s_1$$$ и $$$t_1$$$. Если год увеличивается на один, то мы берем следующую строку по порядку для каждой соответствующей последовательности. Если используемая в данный момент строка находится в конце массива, то переходим к первой строке.</p><p>Например, если $$$n = 3, m = 4, s = $$$<span class="tex-font-style-tt">{«<span class="tex-font-style-tt">a</span>», «<span class="tex-font-style-tt">b</span>», «<span class="tex-font-style-tt">c</span>»}</span>, $$$t =$$$ <span class="tex-font-style-tt">{«<span class="tex-font-style-tt">d</span>», «<span class="tex-font-style-tt">e</span>», «<span class="tex-font-style-tt">f</span>», «<span class="tex-font-style-tt">g</span>»}</span>, то строки для лет с 1 по 14 - <span class="tex-font-style-tt">{«<span class="tex-font-style-tt">ad</span>», «<span class="tex-font-style-tt">be</span>», «<span class="tex-font-style-tt">cf</span>», «<span class="tex-font-style-tt">ag</span>», «<span class="tex-font-style-tt">bd</span>», «<span class="tex-font-style-tt">ce</span>», «<span class="tex-font-style-tt">af</span>», «<span class="tex-font-style-tt">bg</span>», «<span class="tex-font-style-tt">cd</span>», «<span class="tex-font-style-tt">ae</span>», «<span class="tex-font-style-tt">bf</span>», «<span class="tex-font-style-tt">cg</span>», «<span class="tex-font-style-tt">ad</span>», «<span class="tex-font-style-tt">be</span>»}</span>. Обратите внимание, что название года может повторяться.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a0f0fe6cc031a0578f56346ce1e2c8e9368807ae.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Вам даются две последовательности строк размером $$$n$$$ и $$$m$$$, а также $$$q$$$ запросов. Для каждого запроса вам будет указан год. Можете ли вы найти имена, соответствующие данным годам, согласно системе <span class="tex-font-style-it">Gapja</span>?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n, m$$$ ($$$1 \le n, m \le 20$$$).</p><p>Следующая строка содержит $$$n$$$ строк $$$s_1, s_2, \ldots, s_{n}$$$. Каждая строка состоит только из строчных букв алфавита и разделена пробелами. Длина каждой строки не менее $$$1$$$ и не более $$$10$$$.</p><p>Следующая строка содержит $$$m$$$ строк $$$t_1, t_2, \ldots, t_{m}$$$. Каждая строка состоит только из строчных букв алфавита и разделена пробелами. Длина каждой строки не менее $$$1$$$ и не более $$$10$$$.</p><p>Среди заданных $$$n + m$$$ строк могут быть одинаковые (то есть не обязательно они все различны).</p><p>Следующая строка содержит одно целое число $$$q$$$ ($$$1 \le q \le 2\,020$$$).</p><p>В каждой из следующих $$$q$$$ строк записано целое число $$$y$$$ ($$$1 \le y \le 10^9$$$), обозначающее год, про который мы хотим узнать. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк. Для каждой строки выведите название года по описанному выше правилу.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> sinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый пример использует актуальные названия, используемые в системе <span class="tex-font-style-it">Gapja</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:54: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:'812492fe18ff2de7',t:'MTY5NjY2NTI0Ni42MTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*800"]
https://codeforces.com/blog/entry/72804
<!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="17bb3c0a988bbcfabcfbab3b80b286ce"/> <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="Hello 2020 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>Hello 2020 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='17bb3c0a988bbcfabcfbab3b80b286ce'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F72804">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='17bb3c0a988bbcfabcfbab3b80b286ce'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:37:33</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:37:33</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div><div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='17bb3c0a988bbcfabcfbab3b80b286ce'/> <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/ko_osaga">ko_osaga</a></li> <li class="current selectedLava"><a href="/blog/ko_osaga">Blog</a></li> <li><a href="/teams/with/ko_osaga">Teams</a></li> <li><a href="/submissions/ko_osaga">Submissions</a></li> <li><a href="/groups/with/ko_osaga">Groups</a></li> <li><a href="/contests/with/ko_osaga">Contests</a></li> <li><a href="/contests/writer/ko_osaga">Problemsetting</a></li> <li><a href="/streams/ko_osaga">Streams</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ko_osaga" style="text-decoration:none;color:black !important;">ko_osaga's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="73334"> <div class="title"> <a href="/blog/entry/72804"> <p>Hello 2020 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a>, <a href="/topic/73334/en12">history</a>, <span class="format-humantime" title="Jan/04/2020 18:44">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>Since the Polygon tutorial system is currently broken, I will replace the editorial with PDF format. Sorry for the inconvenience!</p><p><a href="https://www.dropbox.com/s/ysttw748rvx46eb/Hello%202020.pdf?dl=0">Solution PDF</a></p><p>Problem A was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203276">Code</a></p><p>Problem B was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203332">Code</a></p><p>Problem C was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203721">Code</a></p><p>Problem D was authored by <a class="rated-user user-orange" href="/profile/nong" title="Master nong">nong</a>. <a href="https://codeforces.com/contest/1284/submission/68203704">Code</a></p><p>Problem E was authored by <a class="rated-user user-orange" href="/profile/ckw1140" title="Master ckw1140">ckw1140</a>. <a href="https://codeforces.com/contest/1284/submission/68203754">Code</a></p><p>Problem F was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203787">Code</a></p><p>Problem G was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203817">Code</a></p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1284" class="notice" style="text-decoration: none;">Hello 2020</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-38652-73334").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "38652", blogEntryId: "72804", 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-73334"><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'>+191</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-73334"><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/ko_osaga"><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/ko_osaga"> ko_osaga </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="Jan/04/2020 18:44">4 years ago</span> </li> <li> <a href="/blog/entry/72804#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/72804#comments"> 157 </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="78289"> <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 (143)</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="570690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SHZhang" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SHZhang" title="International Grandmaster SHZhang" class="rated-user user-red">SHZhang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570690" href="?#comment-570690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570690" class="CommentVoteFrame" data-commentRating="50" data-commentUserId="1150683" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+50</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570690"> <div class="moveup"> <div class="ttypography"><p>When I open the editorial for problem E, I see the editorial for problem C instead. Can the author fix this, please?</p></div> </div> </div> <div class="reply info"> <a class="comment-570690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570690"> <li> <div class="comment"> <table class="comment-table" commentId="570700" commentParentId="570690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570700" href="?#comment-570700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570700" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570700"> <div class="moveup"> <div class="ttypography"><p>Sorry, it's fixed now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570700"> <li> <div class="comment"> <table class="comment-table" commentId="598782" commentParentId="570700"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jokerwyt" style="position: relative;"> <img src='https://userpic.codeforces.org/555567/avatar/247d0346874bdbdd.jpg'/> </a> <div><a href="/profile/jokerwyt" title="Candidate Master jokerwyt" class="rated-user user-violet">jokerwyt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/07/2020 16:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-598782" href="?#comment-598782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570700" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="598782" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555567" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-598782"> <div class="moveup"> <div class="ttypography"><p>Challenge of problem E is nice, but i have no idea how to solve it. Could you provide the solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-598782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-598782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-598782"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/21August" style="position: relative;"> <img src='https://userpic.codeforces.org/452773/avatar/13e016fa74fb3308.jpg'/> </a> <div><a href="/profile/21August" title="Master 21August" class="rated-user user-orange">21August</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570691" href="?#comment-570691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570691" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="452773" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570691"> <div class="moveup"> <div class="ttypography"><p>You got it wrong for E.</p></div> </div> </div> <div class="reply info"> <a class="comment-570691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570691"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570695" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 18:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570695" href="?#comment-570695" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570695" 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-570695"> <div class="moveup"> <div class="ttypography"><p>Really liked problems B and C :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570695"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570706" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TimonKnigge" style="position: relative;"> <img src='https://userpic.codeforces.org/275246/avatar/debe81b88ed671c2.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/TimonKnigge" title="Master TimonKnigge" class="rated-user user-orange">TimonKnigge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570706" href="?#comment-570706" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570706" class="CommentVoteFrame" data-commentRating="86" data-commentUserId="275246" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+86</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570706"> <div class="moveup"> <div class="ttypography"><p>Problem D is a lot more intuitive if you interpret the input as a collection of rectangles, where you are asked if there is a pair of rectangles that overlaps on one axis but not the other. Then a scanline solution is obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-570706 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570706 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570706"> <li> <div class="comment"> <table class="comment-table" commentId="570804" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Skeef79" style="position: relative;"> <img src='https://userpic.codeforces.org/631759/avatar/3033511aaec49179.jpg'/> </a> <div><a href="/profile/Skeef79" title="Candidate Master Skeef79" class="rated-user user-violet">Skeef79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570804" href="?#comment-570804" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570804"> <div class="moveup"> <div class="ttypography"><p>Can you please give some good resources about scanline? </p></div> </div> </div> <div class="reply info"> <a class="comment-570804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570804"> <li> <div class="comment"> <table class="comment-table" commentId="570996" commentParentId="570804"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rezwan.Arefin01" style="position: relative;"> <img src='https://userpic.codeforces.org/358701/avatar/68ec3668b1ccc552.jpg'/> </a> <div><a href="/profile/Rezwan.Arefin01" title="Candidate Master Rezwan.Arefin01" class="rated-user user-violet">Rezwan.Arefin01</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570996" href="?#comment-570996" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570804" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570996" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="358701" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570996"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.topcoder.com/community/competitive-programming/tutorials/line-sweep-algorithms/">Topcoder Tutorials</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570996 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570996 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570996"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570807" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570807" href="?#comment-570807" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570807" class="CommentVoteFrame" data-commentRating="33" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+33</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570807"> <div class="moveup"> <div class="ttypography"><p>That was the original formulation. I came up with the conference statement to make this problem much natural ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-570807 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570807 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570807"> <li> <div class="comment"> <table class="comment-table" commentId="571201" commentParentId="570807"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ghoshsai5000" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ghoshsai5000" title="Pupil ghoshsai5000" class="rated-user user-green">ghoshsai5000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571201" href="?#comment-571201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570807" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571201" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="543439" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571201"> <div class="moveup"> <div class="ttypography"><p>This was eye-opening ! So, the input format is $$$x_1, x_2, y_1, y_2$$$ and we have to look for $$$2$$$ rectangles such that their $$$x$$$-axes coincide but their $$$y$$$ do not or the other way around. </p><p>First time, we sort by $$$x$$$ and for every new line segment we process, we keep track of all the line segments it inserts with. We will check if the corresponding $$$y$$$ of the line segment fits in the bounds of all the line segments it has intersected so far. </p> <ul> <li>$$$y_1$$$ should not be greater than the smallest $$$y_2$$$ seen so far.</li> <li>$$$y_2$$$ should not be lesser than the greatest $$$y_1$$$ seen so far.</li> </ul><p>If you could include this interpretation in the editorial, it would help in understanding a lot :)</p></div> </div> </div> <div class="reply info"> <a class="comment-571201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571201"> <li> <div class="comment"> <table class="comment-table" commentId="571683" commentParentId="571201"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 19:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571683" href="?#comment-571683" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571683" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571683" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571683"> <div class="moveup"> <div class="ttypography"><p>To be honest, I think it very much depends on what you're comfortable with (Specifically, users who love geometry would love this interpretation). For me, it was easier to visualize the problem in the current format (interval format), whereas it took me a while to grasp the rectangle interpretation. It is interesting to see how the problem can be solved in so similar ways for seemingly different interpretations.</p></div> </div> </div> <div class="reply info"> <a class="comment-571683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571683"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="574189" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sthfaceless" style="position: relative;"> <img src='https://userpic.codeforces.org/1176362/avatar/4480df56f05c4612.jpg'/> </a> <div><a href="/profile/sthfaceless" title="Candidate Master sthfaceless" class="rated-user user-violet">sthfaceless</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/18/2020 20:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-574189" href="?#comment-574189" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="574189" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1176362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-574189"> <div class="moveup"> <div class="ttypography"><p>I used it too :)</p></div> </div> </div> <div class="reply info"> <a class="comment-574189 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-574189 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-574189"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570710" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Radewoosh" style="position: relative;"> <img src='https://userpic.codeforces.org/147752/avatar/a91526f3bd0194e8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570710" href="?#comment-570710" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570710" class="CommentVoteFrame" data-commentRating="76" data-commentUserId="147752" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+76</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570710"> <div class="moveup"> <div class="ttypography"><p>When will we be able to submit?</p></div> </div> </div> <div class="reply info"> <a class="comment-570710 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570710 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570710"> <li> <div class="comment"> <table class="comment-table" commentId="570734" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570734" href="?#comment-570734" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570734" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-38" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570734"> <div class="moveup"> <div class="ttypography"><p>In most contests, submission window opens 2 hours after the contest I guess.</p></div> </div> </div> <div class="reply info"> <a class="comment-570734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570734"> <li> <div class="comment"> <table class="comment-table" commentId="570808" commentParentId="570734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WaterColor2037" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/WaterColor2037" title="Master WaterColor2037" class="rated-user user-orange">WaterColor2037</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570808" href="?#comment-570808" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570808" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="876428" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570808"> <div class="moveup"> <div class="ttypography"><p>Why people downvote this?</p></div> </div> </div> <div class="reply info"> <a class="comment-570808 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570808 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570808"> <li> <div class="comment"> <table class="comment-table" commentId="570811" commentParentId="570808"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:40">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570811" href="?#comment-570811" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570808" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570811" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570811"> <div class="moveup"> <div class="ttypography"><p>Because it isn't true. Usually you can submit a few minutes after system tests are over.</p></div> </div> </div> <div class="reply info"> <a class="comment-570811 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570811 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570811"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570748" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570748" href="?#comment-570748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570748" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570748"> <div class="moveup"> <div class="ttypography"><p>Now submission is open.</p></div> </div> </div> <div class="reply info"> <a class="comment-570748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570748"> <li> <div class="comment"> <table class="comment-table" commentId="570761" commentParentId="570748"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570761" href="?#comment-570761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570748" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570761" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570761"> <div class="moveup"> <div class="ttypography"><p>Exactly 2 hours :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570711" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570711" href="?#comment-570711" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570711" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570711"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/72725?#comment-570663">Randomised sol for D</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570711 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570711 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570711"> <li> <div class="comment"> <table class="comment-table" commentId="570714" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570714" href="?#comment-570714" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570714" class="CommentVoteFrame" data-commentRating="59" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+59</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570714"> <div class="moveup"> <div class="ttypography"><p>There is another randomized approach involving hashes. You may assign random number to each lecture and then calculate for each interval the xor of numbers assigned to intervals it intersects. Now you should check that every lecture has same hashes in first and second places...</p></div> </div> </div> <div class="reply info"> <a class="comment-570714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570714"> <li> <div class="comment"> <table class="comment-table" commentId="570730" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570730" href="?#comment-570730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570730"> <div class="moveup"> <div class="ttypography"><p>how do you calculate the xor of the intersections?</p></div> </div> </div> <div class="reply info"> <a class="comment-570730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570730"> <li> <div class="comment"> <table class="comment-table" commentId="570735" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570735" href="?#comment-570735" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570735" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570735" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570735"> <div class="moveup"> <div class="ttypography"><p>I think, scan-line should work. When the interval $$$[l_i,r_i]$$$ opens, you put $$$h_i$$$ in the position $$$r_i$$$ and when this interval closes you take the xor of all numbers on the $$$[l_i, \infty)$$$.</p><p>It should look like <a href="https://ideone.com/Dypu4W">this</a>, but it gets WA-6 and I'm to sleepy to debug it properly.</p></div> </div> </div> <div class="reply info"> <a class="comment-570735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570735"> <li> <div class="comment"> <table class="comment-table" commentId="570764" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570764" href="?#comment-570764" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570764" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570764"> <div class="moveup"> <div class="ttypography"><p>yeah I did same thing but i get wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570764"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571027" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bhj2001" style="position: relative;"> <img src='https://userpic.codeforces.org/602476/avatar/71790bb4a53d93d3.jpg'/> </a> <div><a href="/profile/Bhj2001" title="Master Bhj2001" class="rated-user user-orange">Bhj2001</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571027" href="?#comment-571027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="602476" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571027"> <div class="moveup"> <div class="ttypography"><p>the WA is not because of hash collision <br /> you missed the case when 2 intervals completely overlap</p></div> </div> </div> <div class="reply info"> <a class="comment-571027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571027"> <li> <div class="comment"> <table class="comment-table" commentId="571059" commentParentId="571027"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571059" href="?#comment-571059" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571027" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571059" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571059"> <div class="moveup"> <div class="ttypography"><p>Not really, I just made a silly typo in my segment tree code... I got it accepted now: <a href="/contest/1284/submission/68205086" title="Submission 68205086 by adamant">68205086</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571059 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571059 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571059"> <li> <div class="comment"> <table class="comment-table" commentId="576198" commentParentId="571059"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anodaram" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anodaram" title="International Master anodaram" class="rated-user user-orange">anodaram</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/29/2020 08:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576198" href="?#comment-576198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571059" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576198" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="1314285" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-576198"> <div class="moveup"> <div class="ttypography"><p>Segment Tree is more popular way than multiset for this problem, I think.</p></div> </div> </div> <div class="reply info"> <a class="comment-576198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576198"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570740" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amnesiac_dusk" style="position: relative;"> <img src='https://userpic.codeforces.org/630995/avatar/5c9b8d77d7e96eff.jpg'/> </a> <div><a href="/profile/amnesiac_dusk" title="Grandmaster amnesiac_dusk" class="rated-user user-red">amnesiac_dusk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570740" href="?#comment-570740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570740" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="630995" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570740"> <div class="moveup"> <div class="ttypography"><p>It can also be treated as hashing all maximal cliques of the interval graph which should be sufficient for checking the equality of the graphs as the graph is chordal. My code for reference <a href="/contest/1284/submission/68181402" title="Submission 68181402 by amnesiac_dusk">68181402</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570740"> <li> <div class="comment"> <table class="comment-table" commentId="571137" commentParentId="570740"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tejas_919" style="position: relative;"> <img src='https://userpic.codeforces.org/875719/avatar/25f822a14baf7fbf.jpg'/> </a> <div><a href="/profile/tejas_919" title="Master tejas_919" class="rated-user user-orange">tejas_919</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571137" href="?#comment-571137" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571137" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571137"> <div class="moveup"> <div class="ttypography"><p>Can you tell me where can I learn this stuff about graphs? It would be really helpful of you.</p></div> </div> </div> <div class="reply info"> <a class="comment-571137 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571137 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571137"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570799" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/staniewzki" style="position: relative;"> <img src='https://userpic.codeforces.org/838116/avatar/307490effa9e1ae7.jpg'/> </a> <div><a href="/profile/staniewzki" title="Grandmaster staniewzki" class="rated-user user-red">staniewzki</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570799" href="?#comment-570799" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570799" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838116" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570799"> <div class="moveup"> <div class="ttypography"><p>You can look at my submission, I kept two segment trees — in one i put the value of the lecture on the beggining of the lecture and in the other on the end. Then, for each lecture i checked for lectures than do not intersect, so lectures that have end before the current beggining and the same for other side. </p></div> </div> </div> <div class="reply info"> <a class="comment-570799 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570799 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570799"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571124" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nizil" style="position: relative;"> <img src='https://userpic.codeforces.org/250190/avatar/d1314e6f3fecc96f.jpg'/> </a> <div><a href="/profile/Nizil" title="Expert Nizil" class="rated-user user-blue">Nizil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571124" href="?#comment-571124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571124" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="250190" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571124"> <div class="moveup"> <div class="ttypography"><p>I have a rather neat code doing this that might help: <a href="/contest/1284/submission/68239280" title="Submission 68239280 by Nizil">68239280</a>. I used the formula:</p> <center>$$$\{\text{Lectures that intersect lecture $$$l$$$}\} = \{\text{Lectures that start before $$$l$$$ ends}\} \setminus \{\text{Lectures that end before $$$l$$$ starts}\}$$$</center><p>. Note that if a lecture ends before $$$l$$$ starts, then it also begins before $$$l$$$ ends so in the subtraction every element of the latter set is contained in the former set. Also note that we do a XOR both when we add and when we remove a set.</p></div> </div> </div> <div class="reply info"> <a class="comment-571124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571124"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570746" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570746" href="?#comment-570746" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570746" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570746" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570746"> <div class="moveup"> <div class="ttypography"><p>My solution uses hashes also :)</p><p>Let's calculate value $$$sumA=\sum_{i \, intersects \, j}(h_i\cdot h_j)$$$ by some modulo for segments in A and the same $$$sumB$$$ for segments in B. Here, $$$h_i$$$ are some random values. This can be calculated with scanline. The answer is &quot;YES&quot; iff $$$sumA=sumB$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570746 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570746 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570746"> <li> <div class="comment"> <table class="comment-table" commentId="570766" commentParentId="570746"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570766" href="?#comment-570766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570746" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570766"> <div class="moveup"> <div class="ttypography"><p>yeah me too but i got wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570766"> <li> <div class="comment"> <table class="comment-table" commentId="570861" commentParentId="570766"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570861" href="?#comment-570861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570766" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570861"> <div class="moveup"> <div class="ttypography"><p>Maybe my code will be helpful: <a href="/contest/1284/submission/68181544" title="Submission 68181544 by VladProg">68181544</a></p><p>It doesn't use any data structures. Only two scan lines.</p></div> </div> </div> <div class="reply info"> <a class="comment-570861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570861"> <li> <div class="comment"> <table class="comment-table" commentId="570871" commentParentId="570861"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570871" href="?#comment-570871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570871"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-570871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570871"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570903" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lemelisk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lemelisk" title="Master lemelisk" class="rated-user user-orange">lemelisk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570903" href="?#comment-570903" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570903" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="513315" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570903"> <div class="moveup"> <div class="ttypography"><p>You can just treat intersections as long number in binary notification (zero means no intersection with given index's segment, one means intersection) and use its remainder as hash. See my submission <a href="https://codeforces.com/contest/1284/submission/68191562">https://codeforces.com/contest/1284/submission/68191562</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570903 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570903 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570903"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571092" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571092" href="?#comment-571092" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571092" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571092"> <div class="moveup"> <div class="ttypography"><p>I just leave it here. I also assign random number to each lecture, and then calculate some hashes. But to avoid cases when one segment completely inside in other, I just took complement approach. I get hash of all segments that doesn't intersect with selected. They are those who ends before selected, or starts after selected. So, I have two BIT for each place: one for lectures ending at time X and one for lectures starting at time X. This is done with packed coordinates and four BIT for each set of random identifiers. <a href="/contest/1284/submission/68198554" title="Submission 68198554 by r57shell">68198554</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571092 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571092 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571092"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570994" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570994" href="?#comment-570994" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570994" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570994"> <div class="moveup"> <div class="ttypography"><p>Me too.</p></div> </div> </div> <div class="reply info"> <a class="comment-570994 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570994 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570994"> <li> <div class="comment"> <table class="comment-table" commentId="570995" commentParentId="570994"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570995" href="?#comment-570995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570994" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570995"> <div class="moveup"> <div class="ttypography"><p>My randomised solution also passed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570995"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570712" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/GyojunYoun" style="position: relative;"> <img src='https://userpic.codeforces.org/227186/avatar/84d3b7d6c6ddb05c.jpg'/> </a> <div><a href="/profile/GyojunYoun" title="Grandmaster GyojunYoun" class="rated-user user-red">GyojunYoun</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570712" href="?#comment-570712" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570712" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570712" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="227186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570712"> <div class="moveup"> <div class="ttypography"><p>Thank you for setting these wonderful problems. Unlike other geometry probs, E is so beautiful that I was impressed :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570712 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570712 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570712"> <li> <div class="comment"> <table class="comment-table" commentId="570805" commentParentId="570712"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mango_lassi" style="position: relative;"> <img src='https://userpic.codeforces.org/519408/avatar/69109d1881b4b829.jpg'/> </a> <div><a href="/profile/mango_lassi" title="International Grandmaster mango_lassi" class="rated-user user-red">mango_lassi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570805" href="?#comment-570805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570712" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-29" data-commentUserId="519408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570805"> <div class="moveup"> <div class="ttypography"><p>Just what part of E do you think is beautiful? I agree that the model solution doesn't seem bad, but that is only in comparison to how painful writing code for the not-totally-magic solutions is. A problem with many easy to find ugly solutions does not turn good from the existence of a beautiful solution that is very difficult to find.</p></div> </div> </div> <div class="reply info"> <a class="comment-570805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570805"> <li> <div class="comment"> <table class="comment-table" commentId="570812" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570812" href="?#comment-570812" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570812" class="CommentVoteFrame" data-commentRating="62" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+62</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570812"> <div class="moveup"> <div class="ttypography"><p>I don't get the point. If you failed to find good solution, then it's our fault?</p></div> </div> </div> <div class="reply info"> <a class="comment-570812 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570812 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570812"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570838" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570838" href="?#comment-570838" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570838" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570838" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570838"> <div class="moveup"> <div class="ttypography"><p>Well, I found it really interesting what you can solve it in $$$O(n^2)$$$. <a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a> is really similar problem and I believe it can only be solved in $$$O(n^3)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570838 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570838 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570838"> <li> <div class="comment"> <table class="comment-table" commentId="570840" commentParentId="570838"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570840" href="?#comment-570840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570838" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570840"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-red" href="/profile/OnionPringles" title="International Grandmaster OnionPringles">OnionPringles</a> told me about the $$$O(n^2\log n)$$$ solution of that problem. Of course, it's much harder than our problem's solution, in any aspect.</p></div> </div> </div> <div class="reply info"> <a class="comment-570840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570840"> <li> <div class="comment"> <table class="comment-table" commentId="570867" commentParentId="570840"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570867" href="?#comment-570867" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570867" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570867"> <div class="moveup"> <div class="ttypography"><p>After I found $$$3x_3+4x_4+5x_5$$$ I thought I need $$$x_5$$$... After 4 TLE attempts, I saw the magic :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570867 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570867 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570867"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570722" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iaNTU" style="position: relative;"> <img src='https://userpic.codeforces.org/568681/avatar/e2c4a458dc77ff9b.jpg'/> </a> <div><a href="/profile/iaNTU" title="International Master iaNTU" class="rated-user user-orange">iaNTU</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570722" href="?#comment-570722" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570722" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-15" data-commentUserId="568681" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570722"> <div class="moveup"> <div class="ttypography"><p>Seems like you don't understand what &quot;right after&quot; means.</p></div> </div> </div> <div class="reply info"> <a class="comment-570722 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570722 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570722"> <li> <div class="comment"> <table class="comment-table" commentId="570728" commentParentId="570722"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570728" href="?#comment-570728" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570722" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570728" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-16" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570728"> <div class="moveup"> <div class="ttypography"><p>Right after systest. I'm sorry for F.</p></div> </div> </div> <div class="reply info"> <a class="comment-570728 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570728 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570728"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570739" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570739" href="?#comment-570739" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570739" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570739"> <div class="moveup"> <div class="ttypography"><p>Does the following flow solution for F run in time?</p><p>Create three sets of nodes A, B, and C. A represents the first set of edges, C represents the second set of edges. We need to match as many nodes in A as we can with nodes in C. Set B represents all the nodes in the tree. Each node in A and C will be connected to the two nodes that the edge it represents in connected to. We then run flow from the nodes in A to the nodes in C.</p><p>This graph has O(n) edges and a max flow of O(n).</p></div> </div> </div> <div class="reply info"> <a class="comment-570739 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570739 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570739"> <li> <div class="comment"> <table class="comment-table" commentId="570749" commentParentId="570739"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570749" href="?#comment-570749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570739" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570749"> <div class="moveup"> <div class="ttypography"><p>Actually, nevermind, this just doesn't work</p></div> </div> </div> <div class="reply info"> <a class="comment-570749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570749"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570743" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/snorkel" style="position: relative;"> <img src='https://userpic.codeforces.org/1360865/avatar/4aa0ab75c5725b5.jpg'/> </a> <div><a href="/profile/snorkel" title="Expert snorkel" class="rated-user user-blue">snorkel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570743" href="?#comment-570743" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360865" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570743"> <div class="moveup"> <div class="ttypography"><p>When the codes will be available?</p></div> </div> </div> <div class="reply info"> <a class="comment-570743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570743"> <li> <div class="comment"> <table class="comment-table" commentId="570767" commentParentId="570743"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570767" href="?#comment-570767" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570743" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570767" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570767"> <div class="moveup"> <div class="ttypography"><p>Code is available now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570767"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570750" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570750" href="?#comment-570750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570750" class="CommentVoteFrame" data-commentRating="12" 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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570750"> <div class="moveup"> <div class="ttypography"><p>For F we can prove that answer always equals $$$n - 1$$$ easily using Hall theorem. Pick any $$$k$$$ edges in first tree, we want to prove that there are at least $$$k$$$ edges in the second tree which can be used to replace at least one of picked edges. Let's remove all picked edges from the tree, then it splits to $$$k + 1$$$ components. For each edge in the second tree let's draw an edge between components containing endpoints of the edge. Since the tree was connected before compressing edges it is still connected now, which means it has at least $$$k$$$ edges which are not self-loops, which means there are at least $$$k$$$ edges which can be used to replace one of picked edges.</p></div> </div> </div> <div class="reply info"> <a class="comment-570750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570750"> <li> <div class="comment"> <table class="comment-table" commentId="570752" commentParentId="570750"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 19:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570752" href="?#comment-570752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570750" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570752" 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-570752"> <div class="moveup"> <div class="ttypography"><p>Sadly this proof gives no clue on how to find the matching</p></div> </div> </div> <div class="reply info"> <a class="comment-570752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570752"> <li> <div class="comment"> <table class="comment-table" commentId="570774" commentParentId="570752"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570774" href="?#comment-570774" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570774" 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-570774"> <div class="moveup"> <div class="ttypography"><p>In my solution (tl;dr <a href="https://codeforces.com/blog/entry/72725?#comment-570604">here</a>), it just turns out while I'm looking for some characteristics of the matching that it is perfect, and the argument for that is kinda similar to Hall's theorem — it also deals with sets of edges in T2 and adjacent edges in T1. It doesn't seem to be particularly useful for finding a way to compute a matching quickly, though.</p></div> </div> </div> <div class="reply info"> <a class="comment-570774 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570774 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570774"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570772" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570772" href="?#comment-570772" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570772" class="CommentVoteFrame" data-commentRating="20" 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;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570772"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p><p>Pick a 1 edge (u, v) from the T1, s.t. u is the leaf in T1. We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A). We can find matching, (u, v) in T1 &amp; (u, w) in T2, and remove those edges. For all x($$$x \neq w$$$), if there is a edge (u, x) in T2, we change u to v. it means, remove (u, x) and add(v, x) (step B). As a result, we can remove vertexes u and reduce problem size by one(after operate, T2 remained as tree).</p><p>How to simulate? Bottleneck is the step B, changing (u, x) to (v, x). Therefore we don't change all edges, but simply remove (u, w) and add dummy edge (u, v). We have to find nearest non-dummy edge in step A, but it's all. We can easily do it by Link-Cut Tree</p></div> </div> </div> <div class="reply info"> <a class="comment-570772 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570772 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570772"> <li> <div class="comment"> <table class="comment-table" commentId="570782" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570782" href="?#comment-570782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570782" 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-570782"> <div class="moveup"> <div class="ttypography"><blockquote><p>We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A).</p> </blockquote><p>Tbh when you have this, there's no need for further tricks or LCT. Just HLD over T1, store not yet taken edges in each path in a set (ordered by depth), DFS over T2 and use HLD to simulate the process for each edge in T2. That's my solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-570782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570782"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570785" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OnionPringles" 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/OnionPringles" title="International Grandmaster OnionPringles" class="rated-user user-red">OnionPringles</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570785" href="?#comment-570785" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570785" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="360543" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570785"> <div class="moveup"> <div class="ttypography"><p>I solved step B by merging u,v in T2 by implementing union-find structure on LCT nodes. When merging u and v, cut all preferred children of u and v so that the children can go through union-find structure when they try to access the unpreferred parent. I think it is easy if you have a pre-written LCT code.</p></div> </div> </div> <div class="reply info"> <a class="comment-570785 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570785 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570785"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570791" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gamegame" style="position: relative;"> <img src='https://userpic.codeforces.org/352372/avatar/8717a5b44702348a.jpg'/> </a> <div><a href="/profile/gamegame" title="Legendary Grandmaster gamegame" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>amegame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570791" href="?#comment-570791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="352372" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570791"> <div class="moveup"> <div class="ttypography"><p>You can do binary lifting and dsu, which is much more easier to code than LCT/HLD</p></div> </div> </div> <div class="reply info"> <a class="comment-570791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570791"> <li> <div class="comment"> <table class="comment-table" commentId="571082" commentParentId="570791"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 12:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571082" href="?#comment-571082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570791" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571082" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571082"> <div class="moveup"> <div class="ttypography"><p>I had the same, but tbh in such contests it would be more preferable to just copy LCT.</p></div> </div> </div> <div class="reply info"> <a class="comment-571082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571082"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570884" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570884" href="?#comment-570884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570884" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570884"> <div class="moveup"> <div class="ttypography"><p>I updated my solution to F. It is my favorite in this problem set. Hope you liked it too!</p></div> </div> </div> <div class="reply info"> <a class="comment-570884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570884"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570783" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570783" href="?#comment-570783" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570783" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+61</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570783"> <div class="moveup"> <div class="ttypography"><p>Here is a more intuitive explanation for E. Sorry if it's mentioned already.</p><p>Fix the point $$$p$$$. Translate everything such that $$$p$$$ coincides with the origin. Sort all the other points counter-clockwise. We shall now find the number of quadruples of points that <em>don't</em> form a polygon containing $$$p$$$.</p><p>Now consider some point $$$s$$$. Consider the half-plane $$$H$$$ of points $$$t$$$ such that the cross product $$$s \wedge t$$$ is positive. For a quadrilateral with $$$s$$$ to contain $$$p$$$, it has to have at least one point from $$$H$$$ and at least one point not from $$$H$$$. Conversely, we will count the number of quadruples $$$(s, t_1, t_2, t_3)$$$ such that $$$t_1, t_2, t_3 \in H$$$. It is just the binomial coefficient $$$|H| \choose 3$$$.</p><p>Now do that for all $$$s$$$ and all corresponding $$$H$$$, in linear time, using the two pointers method.</p><p>With iterating over all $$$p$$$ and sorting, the complexity is $$$O (n^2 \log n)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570783 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570783 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570783"> <li> <div class="comment"> <table class="comment-table" commentId="571005" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLamarca" style="position: relative;"> <img src='https://userpic.codeforces.org/379329/avatar/842836a6a188aadb.jpg'/> </a> <div><a href="/profile/VLamarca" title="Master VLamarca" class="rated-user user-orange">VLamarca</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571005" href="?#comment-571005" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571005" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571005" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="379329" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571005"> <div class="moveup"> <div class="ttypography"><p>This solution works for any size of polygon right? For example if the problem was about triangles instead of quadrilaterals</p><p>thanks for sharing it btw </p></div> </div> </div> <div class="reply info"> <a class="comment-571005 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571005 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571005"> <li> <div class="comment"> <table class="comment-table" commentId="571175" commentParentId="571005"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571175" href="?#comment-571175" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571005" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571175" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571175"> <div class="moveup"> <div class="ttypography"><p>Looks like, yeah, the same argument about all points being in one half-plane would work for pentagons and more.</p><p>Now, if the problem asks for <em>convex</em> polygons, it gets trickier, even with quadrilaterals.</p></div> </div> </div> <div class="reply info"> <a class="comment-571175 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571175 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571175"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571064" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Simurgh" style="position: relative;"> <img src='https://userpic.codeforces.org/1365761/avatar/1d3d3be9bd64e4c9.jpg'/> </a> <div><a href="/profile/Simurgh" title="Expert Simurgh" class="rated-user user-blue">Simurgh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571064" href="?#comment-571064" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571064" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1365761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571064"> <div class="moveup"> <div class="ttypography"><p>Where can I learn more about cross products of vectors and how they can be used in geometry problems?</p></div> </div> </div> <div class="reply info"> <a class="comment-571064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571064"> <li> <div class="comment"> <table class="comment-table" commentId="571178" commentParentId="571064"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571178" href="?#comment-571178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571064" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571178"> <div class="moveup"> <div class="ttypography"><p>Basically, scalar product and cross product are similar in behavior to cosine and sine of angle between vectors, respectively. Their signs behave the same.</p><p>The upside is that, more often than not, we are given coordinates of points as integers (or rationals). And computing scalar and cross products can be done using integers only. So we don't have to resort to floating point and then deal with a whole additional class of errors because of loss of precision.</p><p>As for more general overview, a <a href="https://www.google.com/search?q=scalar+product+and+cross+product+in+computational+geometry">Google search</a> lands some nice articles on the first page.</p></div> </div> </div> <div class="reply info"> <a class="comment-571178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571178"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571093" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 13:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571093" href="?#comment-571093" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571093" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571093" class="CommentVoteFrame" data-commentRating="10" 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: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-571093"> <div class="moveup"> <div class="ttypography"><p>How can I actually easily find the sign of the cross product between two vectors? I got an idea of how to do it with the angle between them, but it seems ugly and probably prone to bugs.</p><p>Edit: I found a way on <a href="https://en.wikipedia.org/wiki/Cross_product#Computational_geometry">Wikipedia</a>, scroll down to the Computation Geometry section.</p></div> </div> </div> <div class="reply info"> <a class="comment-571093 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571093 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571093"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570787" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/undisputedAshu" style="position: relative;"> <img src='https://userpic.codeforces.org/327726/avatar/92b4b2153c6ba4e4.jpg'/> </a> <div><a href="/profile/undisputedAshu" title="Pupil undisputedAshu" class="rated-user user-green">undisputedAshu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570787" href="?#comment-570787" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570787" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="327726" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570787"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain for B</p><p>3</p><p>4 2 0 2 0</p><p>6 9 9 8 8 7 7</p><p>1 6</p><p>how is it 7?</p></div> </div> </div> <div class="reply info"> <a class="comment-570787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570787"> <li> <div class="comment"> <table class="comment-table" commentId="570793" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/djm03178" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/djm03178" title="Master djm03178" class="rated-user user-orange">djm03178</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570793" href="?#comment-570793" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570793" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="687688" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570793"> <div class="moveup"> <div class="ttypography"><p>Let's say a = [2,0,2,0], b = [9,9,8,8,7,7], c = [6], then the answers are: aa, ab, ac, ba, bb, ca, and cb.</p></div> </div> </div> <div class="reply info"> <a class="comment-570793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570793"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570794" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gol_en_05" style="position: relative;"> <img src='https://userpic.codeforces.org/838032/avatar/8167074e5c48a57d.jpg'/> </a> <div><a href="/profile/gol_en_05" title="Specialist gol_en_05" class="rated-user user-cyan">gol_en_05</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570794" href="?#comment-570794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570794" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570794"> <div class="moveup"> <div class="ttypography"><p>since 2 0 2 0 has an ascent.so total pairs are 3. 2 nd sequence does not have an ascent but pairs (2,2),(2,1) has ascent. similarly for 3rd sequence pairs(3,1) and(3,2) has ascent. so total 7 pairs are possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-570794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570794"> <li> <div class="comment"> <table class="comment-table" commentId="570904" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570904" href="?#comment-570904" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570904" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570904"> <div class="moveup"> <div class="ttypography"><p>I'm struggling to understand what does &quot;but pairs (2,2),(2,1) has ascent&quot; mean. Can you please elaborate? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-570904 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570904 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570904"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570916" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570916" href="?#comment-570916" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570916" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570916"> <div class="moveup"> <div class="ttypography"><p>Thanks I got it!</p></div> </div> </div> <div class="reply info"> <a class="comment-570916 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570916 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570916"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570795" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BOGDAN_" 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/BOGDAN_" title="Expert BOGDAN_" class="rated-user user-blue">BOGDAN_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570795" href="?#comment-570795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570795" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="635882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570795"> <div class="moveup"> <div class="ttypography"><p>Let 1, 2, 3 — indexes of arrays. Here is &quot;1 + 2&quot;</p><p>&quot;1 + 3&quot;</p><p>&quot;1 + 1&quot;</p><p>&quot;2 + 2&quot;</p><p>&quot;2 + 1&quot;</p><p>&quot;3 + 1&quot;</p><p>&quot;3 + 2&quot;</p><p>At all — answer 7.</p></div> </div> </div> <div class="reply info"> <a class="comment-570795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570803" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Wa-Automaton" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Wa-Automaton" title="Candidate Master Wa-Automaton" class="rated-user user-violet">Wa-Automaton</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570803" href="?#comment-570803" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570803" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570803" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1365147" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570803"> <div class="moveup"> <div class="ttypography"><p>For D, removing operation is at time ea_i + 1 ?</p><p>UPD: It's fixed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570803 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570803 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570803"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570816" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570816" href="?#comment-570816" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570816" 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="570816" 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-570816"> <div class="moveup"> <div class="ttypography"><p>D can be solved using &quot;Job scheduling &quot; algorithm. Initially we check all the intervals for both the venues individually,whether they overlap,if we get different answer,answer is &quot;NO&quot;.</p><p>If we get same answer and both timings of both venues don't overlap,then answer is &quot;YES&quot;.</p><p>If we get &quot;over-lap&quot; for both,there is a possibility that removing some lectures might make one venue overlapping and other non_overlapping</p><p>eg: 1 2 3 4</p> <pre>3 4 4 5 4 5 6 7</pre><p>In this case,we use job scheduling algorithm to find the largest no of lectures that can be present such that,lecture timings don't overlap for venue A.</p><p>Keep only those lectures for B,check if answer is different for both venues,do the same thing for venue B.</p><p><a href="/contest/1284/submission/68206806" title="Submission 68206806 by AjaySabarish">68206806</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570816 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570816 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570816"> <li> <div class="comment"> <table class="comment-table" commentId="571060" commentParentId="570816"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571060" href="?#comment-571060" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570816" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571060" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571060"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/AjaySabarish" title="Expert AjaySabarish">AjaySabarish</a> Hi, can you please explain the part about &quot;non over-lap&quot; in a little detail?How is there a possibility that removing some lectures might make one venue overlapping and other non_overlapping? I also thought about job scheduling algo but as mentioned in comments, did not consider such cases like finding interval in a and then checking them in b and vice versa. Do they both not give same result? </p></div> </div> </div> <div class="reply info"> <a class="comment-571060 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571060 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571060"> <li> <div class="comment"> <table class="comment-table" commentId="571066" commentParentId="571060"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 11:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571066" href="?#comment-571066" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571060" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571066" 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-571066"> <div class="moveup"> <div class="ttypography"><p>Sry there was a typo,now corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-571066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571066"> <li> <div class="comment"> <table class="comment-table" commentId="571198" commentParentId="571066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571198" href="?#comment-571198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571198"> <div class="moveup"> <div class="ttypography"><p>Still can you explain that point about removing some lectures?</p></div> </div> </div> <div class="reply info"> <a class="comment-571198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571198"> <li> <div class="comment"> <table class="comment-table" commentId="571219" commentParentId="571198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571219" href="?#comment-571219" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571219" 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-571219"> <div class="moveup"> <div class="ttypography"><p>Consider the above example,which I gave </p><p>3</p><p>1 2 3 4</p><p>3 4 4 5</p><p>4 5 6 7</p><p>Now,the timings overlap for both venues,but if you remove lecture 3,timings dont overlap for venue A but overlap for venue B.</p><p>This is the last case which I was talking about,now you have to use job scheduling to find the answer.</p><p>Find the highest number of non overlapping segments for A,it is lecture 1,2.</p><p>Now keep only these lectures for both venues,now the segments for B should also not overlap for &quot;not venue sensitive&quot;. But it is overlapping,so it is venue sensitive</p></div> </div> </div> <div class="reply info"> <a class="comment-571219 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571219 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571219"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570825" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SajidZakaria" style="position: relative;"> <img src='https://userpic.codeforces.org/553136/avatar/f6d8cc00ec65b842.jpg'/> </a> <div><a href="/profile/SajidZakaria" title="Candidate Master SajidZakaria" class="rated-user user-violet">SajidZakaria</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570825" href="?#comment-570825" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570825" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="553136" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570825"> <div class="moveup"> <div class="ttypography"><p>The test cases in D were very &quot;weak&quot;. My solution : <a href="/contest/1284/submission/68205621" title="Submission 68205621 by SajidZakaria">68205621</a></p><p>For very large N, it's enough to only check if each of the lectures have the same number of intersections in A and B. Taking advantage of the fact that it's hard to put up a test case that avoids being fooled that way.</p></div> </div> </div> <div class="reply info"> <a class="comment-570825 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570825 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570825"> <li> <div class="comment"> <table class="comment-table" commentId="634898" commentParentId="570825"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Prajwal_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Prajwal_" title="Expert Prajwal_" class="rated-user user-blue">Prajwal_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/02/2020 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-634898" href="?#comment-634898" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570825" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="634898" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360518" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-634898"> <div class="moveup"> <div class="ttypography"><p>but how will you calculate the intersections in O(n) time.Can you explain once more??</p></div> </div> </div> <div class="reply info"> <a class="comment-634898 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-634898 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-634898"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570829" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570829" href="?#comment-570829" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570829" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570829"> <div class="moveup"> <div class="ttypography"><p>Can you share other solutions to E? Except <a class="rated-user user-orange" href="/profile/Gassa" title="International Master Gassa">Gassa</a>'s (above)</p></div> </div> </div> <div class="reply info"> <a class="comment-570829 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570829 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570829"> <li> <div class="comment"> <table class="comment-table" commentId="570852" commentParentId="570829"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570852" href="?#comment-570852" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570829" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570852" 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="570852" class="CommentVoteFrame" data-commentRating="45" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+45</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570852"> <div class="moveup"> <div class="ttypography"><p>I'll put it short:</p> <ul> <li>(By <a class="rated-user user-red" href="/profile/kdh9949" title="International Grandmaster kdh9949">kdh9949</a> <a class="rated-user user-orange" href="/profile/jihoon" title="International Master jihoon">jihoon</a>) Find $$$f(p)$$$ for each point. You can see that the set can enclose $$$p$$$ iff its convex hull contains $$$p$$$. Checking the containment is hard, so sort by angle, and eliminate the set that does not contain $$$p$$$, which reduces to almost similar sweep with model code. I think this is the easiest solution to come up with.</li> <li>(By <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a>) The answer depends on the 2 * (number of convex quadrilaterals) + (number of concave quadrilaterals). We denote this number $$$A$$$. I think the answer is $$$(A - 2\binom{n}{4}) \times (n-4)/2$$$, or something like that. This problem is bit harder, so you need another type of angular sweep like JOI Open 2017 Bulldozer. I think this is more involved to code, but our great tester <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a> took exactly 12 minutes to AC this.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-570852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570852"> <li> <div class="comment"> <table class="comment-table" commentId="571006" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/NoLongerRed" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/NoLongerRed" title="Grandmaster NoLongerRed" class="rated-user user-red">NoLongerRed</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571006" href="?#comment-571006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571006" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="567645" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571006"> <div class="moveup"> <div class="ttypography"><p>My solution is pretty much the same as molamola's solution and I think it is not necessary to do a cool angular sweep:<br />Let $$$X$$$ be the number of $$$((A,B,C),D)$$$ such that $$$D$$$ lies in $$$ABC$$$ and $$$(A,B,C)$$$ is an unordered tuple. The answer is $$$(n-4)X/2$$$.<br />$$$X$$$ can be counted easily: fixing $$$D$$$ and sort other points by the angles, then do a bunch of lower bound.</p></div> </div> </div> <div class="reply info"> <a class="comment-571006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571006"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571012" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571012" href="?#comment-571012" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571012" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571012"> <div class="moveup"> <div class="ttypography"><p>Thanks for sharing. The solution in Editorial really beautiful, but I don't know. Is that possible to came up with such solution in ~1 hour?</p></div> </div> </div> <div class="reply info"> <a class="comment-571012 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571012 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571012"> <li> <div class="comment"> <table class="comment-table" commentId="571014" commentParentId="571012"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571014" href="?#comment-571014" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571012" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571014" 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="571014" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571014"> <div class="moveup"> <div class="ttypography"><p>Actually my solution submitted during the contest is exactly same as the tutorial solution. In fact, I tried to compute all of $$$x$$$, $$$y$$$, and $$$z$$$, so I double-counted not only the edges of the convex hull but also the diagonal edges, to obtain three linear equations.</p> <center>$$$ x + y + z = {n \choose 5} \\ 5x + 4y + 3z = sth \\ 5x + 6y + 7z = sth $$$</center><p>Unfortunately, this linear system was undetermined, and all I can get was $$$(y + 2z)$$$. That was when I felt quite disappointed. But surprisingly, the answer to the problem happened to be exactly $$$(y + 2z)$$$, so I could finally solve the problem.</p><p>At first, I thought I was lucky enough to find a solution with such unsolvable system. So I headed to this tutorial to read the &quot;official&quot; solution, only to find my solution again. Thanks to your question, I found it in the comments :-)</p><p><a href="/contest/1284/submission/68196878" title="Submission 68196878 by jo_on">68196878</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571014 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571014 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571014"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570830" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570830" href="?#comment-570830" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570830" class="CommentVoteFrame" data-commentRating="3" 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: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-570830"> <div class="moveup"> <div class="ttypography"><p>Just curious,did everyone who solved C in contest,prove the solution?It was not so obvious to me,deciphering and processing what a &quot;framed segment&quot; is,took a lot of time.</p><p>Finding pattern was quite difficult,as manually generating test case even for n=4 is difficult</p><p>Lot of people solved it,is there any other idea?</p></div> </div> </div> <div class="reply info"> <a class="comment-570830 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570830 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570830"> <li> <div class="comment"> <table class="comment-table" commentId="570899" commentParentId="570830"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570899" href="?#comment-570899" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570830" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570899" class="CommentVoteFrame" data-commentRating="2" 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:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570899"> <div class="moveup"> <div class="ttypography"><p>Hi, If you now know what a &quot;framed segment&quot; is, then try to formulate number of &quot;framed segment&quot; of a particular length for a given n. For example: if we want to count &quot;framed segement&quot; of length 1. Let's first consider all &quot;framed segment&quot; containing only digit 1. For this &quot;framed segment&quot; to be at leftmost, there are (n — 1)! permutations. Similar argument goes for its other positions as well. This gives us count : (n — 1)! * n. Now, there are total of n single digits like &quot;1&quot; which can make single length &quot;framed segement&quot;. Thus now count for all single length &quot;framed segement&quot; is : (n — 1)! * n * n (something missing?). I have tried to explain the solution with single length fragment above with some details missing which I think you will figure out. Please try to come-up with a general formulation for any &quot;framed segment&quot;length x for a given n. Summing it all up will give you the answer. Link to my submission : <a href="https://codeforces.com/contest/1284/submission/68187501">Here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570899 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570899 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570899"> <li> <div class="comment"> <table class="comment-table" commentId="570912" commentParentId="570899"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570912" href="?#comment-570912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570899" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570912" 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-570912"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot,I get the solution,but I am just curious about the high number of submissions,was it so obvious?did everyone actually prove it or used their intuition to get it?</p></div> </div> </div> <div class="reply info"> <a class="comment-570912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570912"> <li> <div class="comment"> <table class="comment-table" commentId="570917" commentParentId="570912"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570917" href="?#comment-570917" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570912" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570917" 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-570917"> <div class="moveup"> <div class="ttypography"><p>I guess that depends on one's way of counting up to the answer. And from the number of submissions, it feels like people are actually good at counting..:P</p></div> </div> </div> <div class="reply info"> <a class="comment-570917 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570917 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570917"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kiimak" style="position: relative;"> <img src='https://userpic.codeforces.org/780779/avatar/9d6b81e1dd625cd6.jpg'/> </a> <div><a href="/profile/kiimak" title="Candidate Master kiimak" class="rated-user user-violet">kiimak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570849" href="?#comment-570849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570849" 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="570849" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="780779" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570849"> <div class="moveup"> <div class="ttypography"><p>Hi, I think I found a test case for problem D where my solution gets accepted but it should be incorrect.</p> <pre><code>5 1 10 1 10 2 20 11 30 11 30 2 20 21 40 21 40 31 50 31 50 </code></pre><p>I've checked with the code given in the tutorial, the answer is NO, but my solution gives YES. <a href="/contest/1284/submission/68207409" title="Submission 68207409 by kiimak">68207409</a></p><p>I've modeled it as a graph and put an edge (u, v) if lecture u and v meet. I thought it would be enough to check two things for graph A and B (venue A and B)</p> <ul> <li>the number of degrees for each lecture</li> <li>the lecture set of each component</li> </ul><p>I've submitted it after the contest so it doesn't effect my ratings, but I thought it was worth mentioning.</p></div> </div> </div> <div class="reply info"> <a class="comment-570849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570849"> <li> <div class="comment"> <table class="comment-table" commentId="570891" commentParentId="570849"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ormlis" style="position: relative;"> <img src='https://userpic.codeforces.org/1250517/avatar/5b32008c179f4f98.jpg'/> </a> <div><a href="/profile/Ormlis" title="Legendary Grandmaster Ormlis" class="rated-user user-legendary"><span class="legendary-user-first-letter">O</span>rmlis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570891" href="?#comment-570891" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570891" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1250517" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570891"> <div class="moveup"> <div class="ttypography"><p>I made the same mistake. I tried to find a test case where this is not true, but I could not. Thanks you</p></div> </div> </div> <div class="reply info"> <a class="comment-570891 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570891 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570891"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DJoker99" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/DJoker99" title="Pupil DJoker99" class="rated-user user-green">DJoker99</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570865" href="?#comment-570865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570865" 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="570865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="886083" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570865"> <div class="moveup"> <div class="ttypography"><p>Solution for B [Best :- O(n) Worst :- O(nlogn)]</p><p><a href="https://codeforces.com/contest/1284/submission/68210022">https://codeforces.com/contest/1284/submission/68210022</a></p><p>The condition for a non-ascent sequence a and a non-ascen sequence b to form an ascenting sequence is</p><p><code>min(a) &lt;max(b)</code></p> <ol> <li>First traverse the lists and store max and min in two separate vectors.</li> <li>if a sequence has ascent ie if an element greater than current min or current max occurs then that sequence will always give an ascenting sequence hence do <code>cnt = cnt + 2*n-1</code> <code>n--;</code> because that sequence will form 2n-1 sequences on concatenation</li> <li><p>Sort the max and min vectors then use two pointer approach.</p></li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-570865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570865"> <li> <div class="comment"> <table class="comment-table" commentId="570973" commentParentId="570865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 00:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570973" href="?#comment-570973" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570865" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570973" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570973" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570973"> <div class="moveup"> <div class="ttypography"><p>Involving sort gives already nlogn solution) - <a href="https://codeforces.com/contest/1284/submission/68206308">my code</a> — P. S. I have similar solution, but simpler.</p></div> </div> </div> <div class="reply info"> <a class="comment-570973 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570973 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570973"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570877" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prateek_aries" style="position: relative;"> <img src='https://userpic.codeforces.org/780171/avatar/c6136d0edef16466.jpg'/> </a> <div><a href="/profile/prateek_aries" title="Expert prateek_aries" class="rated-user user-blue">prateek_aries</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570877" href="?#comment-570877" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570877" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="780171" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570877"> <div class="moveup"> <div class="ttypography"><p>Someone please explain me the meaning of the last statement in C. &quot;By observing that there exist exactly n−len+1 pairs with 1≤l≤r≤n,r−l+1=len, we can simply multiply this number for each length, giving a O(n) time solution.&quot; Please give any example.</p></div> </div> </div> <div class="reply info"> <a class="comment-570877 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570877 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570877"> <li> <div class="comment"> <table class="comment-table" commentId="570981" commentParentId="570877"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570981" href="?#comment-570981" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570877" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570981" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570981"> <div class="moveup"> <div class="ttypography"><p>Example of what is it about: </p><p>Consider n of 5 and len of 3</p> <ul> <li><p>1 2 3</p></li> <li><p>2 3 4</p></li> <li><p>3 4 5</p></li> </ul><p>Permutate each of them, and you will get all framed subarrays for n and len of the example. </p></div> </div> </div> <div class="reply info"> <a class="comment-570981 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570981 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570981"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570883" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/im_sanyam" style="position: relative;"> <img src='https://userpic.codeforces.org/605247/avatar/6943d67eaf1d4243.jpg'/> </a> <div><a href="/profile/im_sanyam" title="Expert im_sanyam" class="rated-user user-blue">im_sanyam</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570883" href="?#comment-570883" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570883" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="605247" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570883"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain to me the solution of problem C in a better and intuitive way?</p></div> </div> </div> <div class="reply info"> <a class="comment-570883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570883"> <li> <div class="comment"> <table class="comment-table" commentId="570902" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570902" href="?#comment-570902" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570902" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570902" 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-570902"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570902 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570902 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570902"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570911" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/meiniak" style="position: relative;"> <img src='https://userpic.codeforces.org/803808/avatar/924fee722719da18.jpg'/> </a> <div><a href="/profile/meiniak" title="Newbie meiniak" class="rated-user user-gray">meiniak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570911" href="?#comment-570911" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570911" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="803808" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570911"> <div class="moveup"> <div class="ttypography"><p>let's take n = 5. ar = [1,2,3,4,5] . Now iterate for all possible length of sub-array and count number of good sub-array for that length. k = 1, 2, 3 and so on.</p><p>let take say k = 2 and n = 5. So there are n-k+1 position possible to place k elements i.e If we consider [1,2] then we can place [1,2] in position _ 3 _ 4 _ 5 _ and you can select (n-k+1) elements from n elements to i.e [1,2] , [2,3] , [3,4] and [4,5] . So this is how we got (n-k+1) * (n-k+1) and now we just have to count number of possible permutation of k and (n-k) elements left which is nothing but k! and (n-k)! .** (n-k+1) * (n-k+1) * k! * (n-k)!** is the total answer</p></div> </div> </div> <div class="reply info"> <a class="comment-570911 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570911 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570911"> <li> <div class="comment"> <table class="comment-table" commentId="647624" commentParentId="570911"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lazy_learner" style="position: relative;"> <img src='https://userpic.codeforces.org/926934/avatar/1c97e4ddf06e9813.jpg'/> </a> <div><a href="/profile/lazy_learner" title="Newbie lazy_learner" class="rated-user user-gray">lazy_learner</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2020 08:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-647624" href="?#comment-647624" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570911" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="647624" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926934" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-647624"> <div class="moveup"> <div class="ttypography"><p>But would that not lead to overcounting.<br />Consider the case 3 (1 2) 4 5 and 3 1 2 (4 5).<br />These 2 permutations are same and will be counted twice, once when we consider 1,2 together and second when 4,5 are taken together.</p></div> </div> </div> <div class="reply info"> <a class="comment-647624 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-647624 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-647624"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570914" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rover1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rover1" title="Specialist rover1" class="rated-user user-cyan">rover1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570914" href="?#comment-570914" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570914" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1239447" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570914"> <div class="moveup"> <div class="ttypography"><p>If in question C, we have given a permutation of length n then we need to find happiness... Anyone want to share their approaches ..</p></div> </div> </div> <div class="reply info"> <a class="comment-570914 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570914 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570914"> <li> <div class="comment"> <table class="comment-table" commentId="570918" commentParentId="570914"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570918" href="?#comment-570918" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570914" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570918" 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-570918"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570918"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570927" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/M1v1savva1601" style="position: relative;"> <img src='https://userpic.codeforces.org/539005/avatar/21949389dc808e09.jpg'/> </a> <div><a href="/profile/M1v1savva1601" title="Master M1v1savva1601" class="rated-user user-orange">M1v1savva1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570927" href="?#comment-570927" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570927" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="539005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570927"> <div class="moveup"> <div class="ttypography"><p>Shouldn't it be <strong>eai + 1</strong> in D tutorial?</p></div> </div> </div> <div class="reply info"> <a class="comment-570927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570927"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570941" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AwakeAnay" style="position: relative;"> <img src='https://userpic.codeforces.org/666008/avatar/7043fde46ee0493c.jpg'/> </a> <div><a href="/profile/AwakeAnay" title="Grandmaster AwakeAnay" class="rated-user user-red">AwakeAnay</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 23:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570941" href="?#comment-570941" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="666008" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570941"> <div class="moveup"> <div class="ttypography"><p>I had a overkill solution for $$$D$$$ which led to a good data structures problem. While, others have provided much more elegant solutions, this reduced version is a good problem on its own and worth sharing.</p><p>Here's the problem:</p><p>You are given two sequences $$$a_i$$$ and $$$b_i$$$ of length $$$2N$$$ each. Each number from $$$1$$$ to $$$N$$$ appears exactly twice in both the sequences. You have to solve $$$Q$$$ queries of the following kind:</p><p>Given $$$l$$$, $$$r$$$, $$$x$$$ and $$$y$$$, find the set of distinct elements in $$$(l, r)$$$ in $$$a$$$ is exactly equal to the set of distinct elements in $$$(x, y)$$$ in $$$b$$$. That is, any number $$$u$$$ has an appearance in segment $$$(l, r)$$$ in $$$a$$$ if and only if it has an appearance in segment $$$(x, y)$$$ in $$$b$$$. Try to solve this online in $$$O((N+Q)\log(N))$$$.</p><p>Think of how you can reduce today's $$$D$$$ into this problem.</p><p>My code for today's D: <a href="/contest/1284/submission/68189310" title="Submission 68189310 by AwakeAnay">68189310</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570941"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570975" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/madhav_1999" style="position: relative;"> <img src='https://userpic.codeforces.org/594602/avatar/cad96e04d2a42e66.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/madhav_1999" title="Master madhav_1999" class="rated-user user-orange">madhav_1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570975" href="?#comment-570975" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570975" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="594602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570975"> <div class="moveup"> <div class="ttypography"><p>In D: &quot;Event removing interval [sbi, ebi] from S at time ebi+1.&quot;</p><p><a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a>, I think you made an error here, it should be eai + 1 instead</p></div> </div> </div> <div class="reply info"> <a class="comment-570975 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570975 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570975"> <li> <div class="comment"> <table class="comment-table" commentId="571032" commentParentId="570975"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571032" href="?#comment-571032" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570975" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571032" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571032"> <div class="moveup"> <div class="ttypography"><p>Sorry, fixed. </p></div> </div> </div> <div class="reply info"> <a class="comment-571032 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571032 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571032"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570982" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 02:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570982" href="?#comment-570982" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570982" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570982"> <div class="moveup"> <div class="ttypography"><p>Problem B can also be solved in $$$O(n)$$$. Be $$$asc$$$ the number of sequences that have an ascent. For each sequence, check if it's non-increasing. If it isn't any concatenation we do will have an ascent, so we can add $$$n$$$ to our answer and $$$1$$$ to $$$asc$$$. Now be $$$s$$$ a non-increasing sequence and let's set it as the right part of the concatenation. We will only have an ascent in the concatenation if the left part already has an ascent or has an element smaller than any element in $$$s$$$, specially it's maximum. We have $$$asc$$$ sequences of the first type, so that's easy, and for the second part we can precalculate it by creating an array $$$minfreq$$$ where we store the minimum of each non-increasing sequence in it's position (as $$$s_{i,j} &lt; 10^6$$$) and do a sweep from $$$1$$$ to $$$10^6$$$ to accumulate our sum ($$$minfreq[i] = minfreq[i-1] +minfreq[i]$$$). Now we have our answer for the second part in position $$$minfreq[max(s)-1]$$$, and we can just add both parts to our answer. Since we can precalculate $$$minfreq$$$, $$$max(s)$$$ and $$$asc$$$ in $$$O(n)$$$ and the answer can be calculated in $$$O(1)$$$ using our precalculations total complexity is $$$O(n)$$$ </p></div> </div> </div> <div class="reply info"> <a class="comment-570982 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570982 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570982"> <li> <div class="comment"> <table class="comment-table" commentId="570987" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dblark" style="position: relative;"> <img src='https://userpic.codeforces.org/693276/avatar/70323ef41e4c9add.jpg'/> </a> <div><a href="/profile/dblark" title="International Master dblark" class="rated-user user-orange">dblark</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 03:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570987" href="?#comment-570987" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570987" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="693276" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570987"> <div class="moveup"> <div class="ttypography"><p>Yeah, the same idea with you!</p></div> </div> </div> <div class="reply info"> <a class="comment-570987 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570987 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570987"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571037" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 08:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571037" href="?#comment-571037" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571037" class="CommentVoteFrame" data-commentRating="0" 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:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571037"> <div class="moveup"> <div class="ttypography"><p>I did the same, but this is not O(N). The time Complexity will be O(n + maxELE) where maxELE is the largest sequence element seen in input.</p><p>We were lucky that the constraint on that wasn't 10^9.</p><p>Also consider cases in which n = 5 but the elements are still very large, our code would still take lot of time to execute.</p></div> </div> </div> <div class="reply info"> <a class="comment-571037 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571037 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571037"> <li> <div class="comment"> <table class="comment-table" commentId="571654" commentParentId="571037"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 18:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571654" href="?#comment-571654" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571037" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571654" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571654"> <div class="moveup"> <div class="ttypography"><p>Yeah that's true, the editorial's solution is more general for that same reason</p></div> </div> </div> <div class="reply info"> <a class="comment-571654 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571654 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571654"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571551" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571551" href="?#comment-571551" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571551" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571551"> <div class="moveup"> <div class="ttypography"><p>I cant understand the minfreq[i]=minfreq[i−1]+minfreq[i] . can you explain me </p></div> </div> </div> <div class="reply info"> <a class="comment-571551 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571551 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571551"> <li> <div class="comment"> <table class="comment-table" commentId="571653" commentParentId="571551"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571653" href="?#comment-571653" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571551" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571653" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571653"> <div class="moveup"> <div class="ttypography"><p>It's called accumulated sum. Basically we want minfreq[i] to be the frequency of all numbers $$$\leq$$$ to i, so we need to push our previous array position to our current one, so that we also take into account the occurences of numbers &lt; i, and not just equal to i</p></div> </div> </div> <div class="reply info"> <a class="comment-571653 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571653 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571653"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571001" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Aguin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Aguin" title="Candidate Master Aguin" class="rated-user user-violet">Aguin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571001" href="?#comment-571001" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571001" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="297931" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571001"> <div class="moveup"> <div class="ttypography"><p>How to count different quadrilaterals in problem E?</p></div> </div> </div> <div class="reply info"> <a class="comment-571001 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571001 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571001"> <li> <div class="comment"> <table class="comment-table" commentId="571004" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571004" href="?#comment-571004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571004"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571004"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571007" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 05:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571007" href="?#comment-571007" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571007" class="CommentVoteFrame" data-commentRating="3" 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;">+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-571007"> <div class="moveup"> <div class="ttypography"><p>For example, for each pair of points $$$(i, j)$$$, we can find the number of points on one side of the line i-j ($$$a$$$), the number of points on the other side ($$$N-2-a$$$), sum that up, divide by 2 and subtract $$$2{N\choose 4}$$$. Why? For each 4-tuple of points, if one of them is inside the triangle formed by the other 3 (their convex hull is a triangle), we get 3 lines (inner point, some other point) that are counted here, and when their convex hull is a quadrilateral, we get 2 such lines — its diagonals; we subtract (2 * number of 4-tuples) to get the number of 4-tuples where one point is inside.</p><p>How to find these $$$a$$$ for each pair $$$(i, j)$$$ fast? Let's say that $$$i$$$ is fixed, sort all remaining points by their angle around point $$$i$$$, then consider a line that crosses $$$i$$$, start rotating it and whenever it crosses one of these points, update the current value of $$$a$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-571007 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571007 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571007"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571011" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571011" href="?#comment-571011" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571011" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571011"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> (<a href="/topic/73334/en9">previous revision</a>, <a href="/topic/73334/en10">new revision</a>, <a href="/topic/73334/diff/en9/en10">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-571011 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571011 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571011"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hd7" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Hd7" title="Specialist Hd7" class="rated-user user-cyan">Hd7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571018" href="?#comment-571018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571018" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="559666" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571018"> <div class="moveup"> <div class="ttypography"><p>Could anyone give me a more elaborated explanation for problem D, I didn't grasp the editorial at all.</p></div> </div> </div> <div class="reply info"> <a class="comment-571018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571031" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571031" href="?#comment-571031" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571031" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571031"> <div class="moveup"> <div class="ttypography"><p>Expected a matroid problem, as <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> took matroid class last semester XD</p></div> </div> </div> <div class="reply info"> <a class="comment-571031 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571031 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571031"> <li> <div class="comment"> <table class="comment-table" commentId="571033" commentParentId="571031"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571033" href="?#comment-571033" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571031" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571033" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571033"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/team/65651">matroid fan club!</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571033 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571033 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571033"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571040" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PouyaNavid" style="position: relative;"> <img src='https://userpic.codeforces.org/670316/avatar/c42e949ea38011da.jpg'/> </a> <div><a href="/profile/PouyaNavid" title="Master PouyaNavid" class="rated-user user-orange">PouyaNavid</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 09:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571040" href="?#comment-571040" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571040" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="670316" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571040"> <div class="moveup"> <div class="ttypography"><p>Hack Test for D <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a></p><p>4 1 10 51 60 2 20 44 52 3 40 43 45 42 45 50 50</p></div> </div> </div> <div class="reply info"> <a class="comment-571040 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571040 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571040"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571088" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hazyknight" style="position: relative;"> <img src='https://userpic.codeforces.org/537474/avatar/e2c88ee4c2562699.jpg'/> </a> <div><a href="/profile/Hazyknight" title="International Grandmaster Hazyknight" class="rated-user user-red">Hazyknight</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571088" href="?#comment-571088" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571088" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571088" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="537474" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571088"> <div class="moveup"> <div class="ttypography"><p>Actually, Problem G can be solved easily by matroid intersection. Consider two matroid M1(S,I),M2(S,I), S is the set of wall, M1 is a graph matroid , M2 is a matroid which any black cell has at least to side without wall. Code: <a href="https://codeforces.com/contest/1284/submission/68215804">https://codeforces.com/contest/1284/submission/68215804</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571088 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571088 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571088"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571128" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amstan" style="position: relative;"> <img src='https://userpic.codeforces.org/734003/avatar/344c500da9a98a7f.jpg'/> </a> <div><a href="/profile/amstan" title="Expert amstan" class="rated-user user-blue">amstan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571128" href="?#comment-571128" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571128" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="734003" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571128"> <div class="moveup"> <div class="ttypography"><p>Is there anyone who solved D using coordinate compression and prefix sum ? If so, could you please share your submission.</p></div> </div> </div> <div class="reply info"> <a class="comment-571128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571128"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571138" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HaoxuanXIE" style="position: relative;"> <img src='https://userpic.codeforces.org/1234114/avatar/fa4b56dfead7992e.jpg'/> </a> <div><a href="/profile/HaoxuanXIE" title="Expert HaoxuanXIE" class="rated-user user-blue">HaoxuanXIE</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571138" href="?#comment-571138" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571138" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1234114" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571138"> <div class="moveup"> <div class="ttypography"><p>Why does D need to check in two directions? If I check in one direction, I get wrong answer at 9th point. But I think it is appropriate to check in only one direction.</p></div> </div> </div> <div class="reply info"> <a class="comment-571138 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571138 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571138"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571145" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheeLooser" style="position: relative;"> <img src='https://userpic.codeforces.org/448032/avatar/d5dcfa8c5dbd255f.jpg'/> </a> <div><a href="/profile/TheeLooser" title="Expert TheeLooser" class="rated-user user-blue">TheeLooser</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571145" href="?#comment-571145" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571145" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="448032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571145"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> may as well check how many visits were made to <a href="https://codeforces.com/problemset/problem/1146/H">this</a> page and later to <a href="https://codeforces.com/blog/entry/66639">this</a> page in contest time</p></div> </div> </div> <div class="reply info"> <a class="comment-571145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571145"> <li> <div class="comment"> <table class="comment-table" commentId="571459" commentParentId="571145"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 22:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571459" href="?#comment-571459" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571145" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571459" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571459"> <div class="moveup"> <div class="ttypography"><p>How does that problem help?</p></div> </div> </div> <div class="reply info"> <a class="comment-571459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571459"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571509" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Petr" style="position: relative;"> <img src='https://userpic.codeforces.org/664/avatar/a113c1791cdcd2e1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Petr" title="Legendary Grandmaster Petr" class="rated-user user-legendary"><span class="legendary-user-first-letter">P</span>etr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 01:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571509" href="?#comment-571509" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571509" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="664" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571509"> <div class="moveup"> <div class="ttypography"><p>Re: &quot;Hopefully, the first 80 tests were good enough for the contest.&quot;</p><p>My <a href="https://codeforces.com/contest/1284/submission/68208450">random solution</a> fails on test 87 :) Great job making the tests indeed!</p></div> </div> </div> <div class="reply info"> <a class="comment-571509 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571509 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571509"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571522" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MubtasimShahriar" style="position: relative;"> <img src='https://userpic.codeforces.org/756984/avatar/9113baa4abf04299.jpg'/> </a> <div><a href="/profile/MubtasimShahriar" title="Pupil MubtasimShahriar" class="rated-user user-green">MubtasimShahriar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 05:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571522" href="?#comment-571522" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571522" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756984" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571522"> <div class="moveup"> <div class="ttypography"><p>In Problem D, why does this solution not work? My Solutions is this.</p><p>Sort lectures according to their start-ending time in both venue, Then decide every lecture if it intersects with others in their own venue.</p><p>If there is at least one lecture that make difference in intersecting in both venue, then Subset can not be made. So the answer is no. If every problem either intersects in both venue or does not intersect in both venue then answer is yes. Here is my implementation <a href="/contest/1284/submission/68294866" title="Submission 68294866 by MubtasimShahriar">68294866</a></p><p>Please someone enlighten me where I am misunderstanding.</p></div> </div> </div> <div class="reply info"> <a class="comment-571522 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571522 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571522"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571546" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SLIMSHADYNICK" style="position: relative;"> <img src='https://userpic.codeforces.org/598862/avatar/7629f1b29f0fe807.jpg'/> </a> <div><a href="/profile/SLIMSHADYNICK" title="Candidate Master SLIMSHADYNICK" class="rated-user user-violet">SLIMSHADYNICK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571546" href="?#comment-571546" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571546" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-13" data-commentUserId="598862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-571546"> <div class="moveup"> <div class="ttypography"><p>In problem D, I got wrong answer on test case 14. Can somebody please help.</p></div> </div> </div> <div class="reply info"> <a class="comment-571546 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571546 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571546"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572491" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ftiasch" style="position: relative;"> <img src='https://userpic.codeforces.org/506/avatar/c52be21fbeb4a450.jpg'/> </a> <div><a href="/profile/ftiasch" title="International Grandmaster ftiasch" class="rated-user user-red">ftiasch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/11/2020 00:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572491" href="?#comment-572491" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572491" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="506" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-572491"> <div class="moveup"> <div class="ttypography"><p>2020 begins with two matroid problems. XD</p><p>btw, Challenge in Problem F is called Strong Basis Exchange as in <a href="https://math.mit.edu/~goemans/18438F09/lec11.pdf">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-572491 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572491 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572491"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572780" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Akash79" style="position: relative;"> <img src='https://userpic.codeforces.org/776725/avatar/700a28ac96121584.jpg'/> </a> <div><a href="/profile/Akash79" title="Expert Akash79" class="rated-user user-blue">Akash79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 16:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572780" href="?#comment-572780" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572780" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="776725" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572780"> <div class="moveup"> <div class="ttypography"><p>I am not able to understand problem B's solution.. can anyone please help me out..??</p></div> </div> </div> <div class="reply info"> <a class="comment-572780 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572780 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572780"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 17:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572849" href="?#comment-572849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="572849" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="572849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572849"> <div class="moveup"> <div class="ttypography"><p>Why don't we have to consider the case when there's some period intersecting in A and not intersecting in B? Doesn't that mean that sometimes our code will say 'YES' but the answer is 'NO'. Why? <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a>. EDIT: Ok, I just didn't notice the part of the code where he does the same thing but reversed.</p></div> </div> </div> <div class="reply info"> <a class="comment-572849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572849"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572863" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 18:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572863" href="?#comment-572863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572863" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572863"> <div class="moveup"> <div class="ttypography"><p>What is the hash approach for the problem D?</p></div> </div> </div> <div class="reply info"> <a class="comment-572863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572863"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="576477" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anaksoleh" style="position: relative;"> <img src='https://userpic.codeforces.org/1170460/avatar/27d790d7abbbd3d9.jpg'/> </a> <div><a href="/profile/anaksoleh" title="Newbie anaksoleh" class="rated-user user-gray">anaksoleh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/30/2020 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576477" href="?#comment-576477" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576477" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170460" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-576477"> <div class="moveup"> <div class="ttypography"><p>there is a proof for C solution ?</p></div> </div> </div> <div class="reply info"> <a class="comment-576477 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576477 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576477"> <li> <div class="comment"> <table class="comment-table" commentId="673042" commentParentId="576477"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/XORring-Samurai" style="position: relative;"> <img src='https://userpic.codeforces.org/1384228/avatar/d0258d5ed6604923.jpg'/> </a> <div><a href="/profile/XORring-Samurai" title="Candidate Master XORring-Samurai" class="rated-user user-violet">XORring-Samurai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/02/2020 09:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-673042" href="?#comment-673042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-576477" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="673042" 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="673042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1384228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-673042"> <div class="moveup"> <div class="ttypography"><p>Here is something, that I could think of.</p><p>For each permutation, we have the same $$$r-l$$$. This value varies from $$$0$$$ to $$$n-1$$$ for all $$$n$$$. Now let us consider $$$r-l=d$$$, as a general case. </p><p>For each $$$n$$$, we have $$$n-d$$$ pairs of $$$[l, r]$$$, where $$$r-l=d$$$. Also for all numbers from $$$1$$$ to $$$n$$$, we have $$$n-d$$$ pairs of type $$$[i, j]$$$ such that $$$j-i=d$$$. </p><p>For a segment to be framed, all the other places for each $$$[l, r]$$$ must be occupied by each integer from $$$[i, j]$$$. Therefore, we have $$$d+1$$$ numbers to be arranged in this interval $$$[l, r]$$$ and $$$n-d-1$$$ to be arranged in $$$[1, l-1]$$$ and $$$[r+1, n]$$$. This can be done in $$$(d+1)! * (n-d-1)!$$$ ways. </p><p>But we have $$$n-d$$$ pairs of $$$[l, r]$$$ and $$$n-d$$$ pairs of $$$[i, j]$$$, each of which can occupy this segment. Therefore the answer becomes summation over all $$$d$$$ from $$$0$$$ to $$$n-1$$$: $$$ans = ans + (n-d) * (n-d) * (d+1)! * (n-d-1)!$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-673042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-673042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-673042"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606852" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ThakurSaab" style="position: relative;"> <img src='https://userpic.codeforces.org/1267713/avatar/7c6c4d7b58cddb96.jpg'/> </a> <div><a href="/profile/ThakurSaab" title="Expert ThakurSaab" class="rated-user user-blue">ThakurSaab</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 17:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606852" href="?#comment-606852" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606852" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1267713" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606852"> <div class="moveup"> <div class="ttypography"><p>In problem C , do we consider that the numbers inside a particular segment [l,r] could be different such that, max-min = r-l</p></div> </div> </div> <div class="reply info"> <a class="comment-606852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606852"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="689589" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 07:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689589" href="?#comment-689589" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689589" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689589"> <div class="moveup"> <div class="ttypography"><p>In Problem D I added elements in the segment tree in the decreasing order of eai and then I queried for the previous range if the min of the ls and the maxr intersect with the particular index of a I am addding . I am getting a WA at Test Case 7 for this submission.</p><p>This is my submission link: <a href="https://codeforces.com/contest/1284/submission/91535000">https://codeforces.com/contest/1284/submission/91535000</a></p><p>Can somebody help me with this solution where I went wrong? </p><p>Or is there anyway I can look at the whole testcase then please reply here about how can I do that?</p></div> </div> </div> <div class="reply info"> <a class="comment-689589 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689589 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689589"> <li> <div class="comment"> <table class="comment-table" commentId="689595" commentParentId="689589"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 08:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689595" href="?#comment-689595" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-689589" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689595" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689595"> <div class="moveup"> <div class="ttypography"><p>Never Mind I made a silly typo in the cmp2 function.</p></div> </div> </div> <div class="reply info"> <a class="comment-689595 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689595 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689595"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="722358" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tanishq_code_c" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tanishq_code_c" title="Expert tanishq_code_c" class="rated-user user-blue">tanishq_code_c</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/17/2020 17:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-722358" href="?#comment-722358" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="722358" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1484322" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-722358"> <div class="moveup"> <div class="ttypography"><p>Hi, I am not able to understand the editorial for problem C. can anyone break it down in easy way please ? </p></div> </div> </div> <div class="reply info"> <a class="comment-722358 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-722358 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-722358"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="736312" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheOneYouWant" style="position: relative;"> <img src='https://userpic.codeforces.org/628619/avatar/c785428bde285c3.jpg'/> </a> <div><a href="/profile/TheOneYouWant" title="Master TheOneYouWant" class="rated-user user-orange">TheOneYouWant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/23/2020 05:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-736312" href="?#comment-736312" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="736312" class="CommentVoteFrame" data-commentRating="91" data-commentUserId="628619" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+91</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-736312"> <div class="moveup"> <div class="ttypography"><p>Hello, this seems to be broken (perhaps a sign of how the year 2020 has been so far)</p></div> </div> </div> <div class="reply info"> <a class="comment-736312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-736312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-736312"> <li> <div class="comment"> <table class="comment-table" commentId="737407" commentParentId="736312"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/27/2020 09:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-737407" href="?#comment-737407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-736312" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="737407" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-737407"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> please take a look, thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-737407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-737407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-737407"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741444" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/butterflies" style="position: relative;"> <img src='https://userpic.codeforces.org/1651561/avatar/33dfc9c16e5795ad.jpg'/> </a> <div><a href="/profile/butterflies" title="Specialist butterflies" class="rated-user user-cyan">butterflies</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741444" href="?#comment-741444" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="741444" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="741444" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1651561" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741444"> <div class="moveup"> <div class="ttypography"><p>This question relates to <a href="https://codeforces.com/contest/1284/problem/B">problem B</a>. I have a question with the second example input. Here is the input:</p> <pre><code>3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 </code></pre><p>I believe all arrays have an ascent. In the first array, the pair $$$(i, j) = (3, 4)$$$ works. ($$$a_3 = 0, a_4 = 2.$$$) In the second array, the pair $$$(i, j) = (1, 2)$$$ works. ($$$a_1 = 6, a_2 = 9.$$$) In the third array, the pair $$$(i,j) = (1, 2)$$$ works. ($$$a_1 = 1, a_2 = 6.$$$)</p><p>Thus, shouldn't all pairs of arrays in this case work? There are $$$9$$$ such pairs, but the answer to this should be $$$7.$$$ What is wrong with my reasoning here?</p></div> </div> </div> <div class="reply info"> <a class="comment-741444 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741444 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741444"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741445" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/beetroot" style="position: relative;"> <img src='https://userpic.codeforces.org/1503072/avatar/6668dbf5be4e4495.jpg'/> </a> <div><a href="/profile/beetroot" title="Expert beetroot" class="rated-user user-blue">beetroot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741445" href="?#comment-741445" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741445" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1503072" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741445"> <div class="moveup"> <div class="ttypography"><p>Editorials that didn't age well...</p></div> </div> </div> <div class="reply info"> <a class="comment-741445 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741445 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741445"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741475" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 07:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741475" href="?#comment-741475" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741475" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741475"> <div class="moveup"> <div class="ttypography"><p>Sorry for the issue with editorials. I think there is a timeout issue from Polygon. Since I can't resolve it, I will just rewrite it as a PDF form and upload here.</p></div> </div> </div> <div class="reply info"> <a class="comment-741475 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741475 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741475"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="797067" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/YPK" style="position: relative;"> <img src='https://userpic.codeforces.org/1489397/avatar/bd42de2aca7084dd.jpg'/> </a> <div><a href="/profile/YPK" title="Master YPK" class="rated-user user-orange">YPK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/29/2021 11:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-797067" href="?#comment-797067" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="797067" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="797067" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1489397" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-797067"> <div class="moveup"> <div class="ttypography"><p>Weak test cases for D. Consider the following test case </p> <pre><code>3 1 3 1 2 4 6 4 5 5 7 2 3 </code></pre><p>My accepted solution gives YES but the answer is NO.</p></div> </div> </div> <div class="reply info"> <a class="comment-797067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-797067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-797067"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="891199" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav04" style="position: relative;"> <img src='https://userpic.codeforces.org/2093148/avatar/b05253879beed26d.jpg'/> </a> <div><a href="/profile/abhinav04" title="Specialist abhinav04" class="rated-user user-cyan">abhinav04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/27/2022 11:56">19 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-891199" href="?#comment-891199" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="891199" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="2093148" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-891199"> <div class="moveup"> <div class="ttypography"><p>In case someone needs help with problem B, this might help.</p> <div class="spoiler"><b class="spoiler-title">submission</b><div class="spoiler-content" style="display: none;"><p><a href="https://codeforces.com/contest/1284/submission/147841447">https://codeforces.com/contest/1284/submission/147841447</a></p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-891199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-891199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-891199"> </ul> </div> <br/> <div id="editBox-78289" 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 firstPreview78289 = true; var lastPreviewContent78289 = ''; 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=78289] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=78289] 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-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, 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:27:29</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81288aad58e60057',t:'MTY5NjcwNjg0OS42NzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1284B
1284
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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Последовательность $$$a = [a_1, a_2, \ldots, a_l]$$$ длиной $$$l$$$ имеет <span class="tex-font-style-bf">восход</span>, если существует пара таких индексов $$$(i, j)$$$, что $$$1 \le i &lt; j \le l$$$ и $$$a_i &lt; a_j$$$. Например, последовательность $$$[0, 2, 0, 2, 0]$$$ имеет восход из-за пары индексов $$$(1, 4)$$$, но последовательность $$$[4, 3, 3, 3, 1]$$$ не имеет восхода.</p><p>Назовем конкатенацией двух последовательностей $$$p$$$ и $$$q$$$ такую последовательность, которая получится при последовательной записи сначала $$$p$$$, затем $$$q$$$ друг за другом, не меняя порядок элементов в них. Например, конкатенация последовательностей $$$[0, 2, 0, 2, 0]$$$ и $$$[4, 3, 3, 3, 1]$$$ равна последовательности $$$[0, 2, 0, 2, 0, 4, 3, 3, 3, 1]$$$. Конкатенация последовательностей $$$p$$$ и $$$q$$$ обозначается как $$$p+q$$$.</p><p>Кенгун считает, что последовательность с восходом приносит удачу. Поэтому он хочет сделать много таких последовательностей на новый год. У Кенгун есть $$$n$$$ последовательностей $$$s_1, s_2, \ldots, s_n$$$, которые могут иметь разную длину.</p><p>Кенгун рассмотрит $$$n^2$$$ всевозможных пар последовательностей $$$s_x$$$ и $$$s_y$$$ ($$$1 \le x, y \le n$$$) и проверит содержит ли конкатенация $$$s_x + s_y$$$ восход или нет. Обратите внимание, что порядок выбора последовательностей в пару имеет значение. Кроме того, он может выбирать последовательность в пару к самой себе.</p><p>Пожалуйста, посчитайте количество пар последовательностей ($$$x, y$$$) для заданного набора $$$s_1, s_2, \ldots, s_n$$$, конкатенация $$$s_x + s_y$$$ которых имеет восход.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 100\,000$$$), обозначающее количество последовательностей.</p><p>В каждой из следующих $$$n$$$ строк записано целое число $$$l_i$$$ ($$$1 \le l_i$$$), обозначающее длину $$$s_i$$$, после которой записано $$$l_i$$$ целых чисел $$$s_{i, 1}, s_{i, 2}, \ldots, s_{i, l_i}$$$ ($$$0 \le s_{i, j} \le 10^6$$$), обозначающие последовательность $$$s_i$$$.</p><p>Гарантируется, что сумма всех $$$l_i$$$ не превосходит $$$100\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, количество пар последовательностей, конкатенация которых имеет восход.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 1 1 1 1 2 1 4 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 72 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, следующие $$$9$$$ последовательностей имеют восход: $$$[1, 2], [1, 2], [1, 3], [1, 3], [1, 4], [1, 4], [2, 3], [2, 4], [3, 4]$$$. Одинаковые по содержимому последовательности учитываются столько раз, сколько раз они встречаются как результат конкатенации.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="bb58774dfe9c1a4d1f3067bcef28dac8"/> <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="844107ee75ef6ee8a5d433a0bcfbbda150cb7f74"/> <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='bb58774dfe9c1a4d1f3067bcef28dac8'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1284%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='bb58774dfe9c1a4d1f3067bcef28dac8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1284">Hello 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='bb58774dfe9c1a4d1f3067bcef28dac8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1284/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='bb58774dfe9c1a4d1f3067bcef28dac8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="508363"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bb58774dfe9c1a4d1f3067bcef28dac8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="508363"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72725" title="Hello 2020" target="_blank">Hello 2020 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10228" resourceName="Hello 2020" resourceManual="true" src="//codeforces.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/72804" title="Hello 2020 Editorial" target="_blank">Hello 2020 Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10239" resourceName="Hello 2020 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/1284">Задачи</a></li> <li><a href="/contest/1284/submit">Отослать</a></li> <li><a href="/contest/1284/my">Мои посылки</a></li> <li><a href="/contest/1284/status">Статус</a></li> <li><a href="/contest/1284/hacks">Взломы</a></li> <li><a href="/contest/1284/room/1">Комната</a></li> <li><a href="/contest/1284/standings">Положение</a></li> <li><a href="/contest/1284/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d2763c8a7d936f6a5a5846b36b3ec5e2df379c64"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Последовательность $$$a = [a_1, a_2, \ldots, a_l]$$$ длиной $$$l$$$ имеет <span class="tex-font-style-bf">восход</span>, если существует пара таких индексов $$$(i, j)$$$, что $$$1 \le i &lt; j \le l$$$ и $$$a_i &lt; a_j$$$. Например, последовательность $$$[0, 2, 0, 2, 0]$$$ имеет восход из-за пары индексов $$$(1, 4)$$$, но последовательность $$$[4, 3, 3, 3, 1]$$$ не имеет восхода.</p><p>Назовем конкатенацией двух последовательностей $$$p$$$ и $$$q$$$ такую последовательность, которая получится при последовательной записи сначала $$$p$$$, затем $$$q$$$ друг за другом, не меняя порядок элементов в них. Например, конкатенация последовательностей $$$[0, 2, 0, 2, 0]$$$ и $$$[4, 3, 3, 3, 1]$$$ равна последовательности $$$[0, 2, 0, 2, 0, 4, 3, 3, 3, 1]$$$. Конкатенация последовательностей $$$p$$$ и $$$q$$$ обозначается как $$$p+q$$$.</p><p>Кенгун считает, что последовательность с восходом приносит удачу. Поэтому он хочет сделать много таких последовательностей на новый год. У Кенгун есть $$$n$$$ последовательностей $$$s_1, s_2, \ldots, s_n$$$, которые могут иметь разную длину.</p><p>Кенгун рассмотрит $$$n^2$$$ всевозможных пар последовательностей $$$s_x$$$ и $$$s_y$$$ ($$$1 \le x, y \le n$$$) и проверит содержит ли конкатенация $$$s_x + s_y$$$ восход или нет. Обратите внимание, что порядок выбора последовательностей в пару имеет значение. Кроме того, он может выбирать последовательность в пару к самой себе.</p><p>Пожалуйста, посчитайте количество пар последовательностей ($$$x, y$$$) для заданного набора $$$s_1, s_2, \ldots, s_n$$$, конкатенация $$$s_x + s_y$$$ которых имеет восход.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 100\,000$$$), обозначающее количество последовательностей.</p><p>В каждой из следующих $$$n$$$ строк записано целое число $$$l_i$$$ ($$$1 \le l_i$$$), обозначающее длину $$$s_i$$$, после которой записано $$$l_i$$$ целых чисел $$$s_{i, 1}, s_{i, 2}, \ldots, s_{i, l_i}$$$ ($$$0 \le s_{i, j} \le 10^6$$$), обозначающие последовательность $$$s_i$$$.</p><p>Гарантируется, что сумма всех $$$l_i$$$ не превосходит $$$100\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, количество пар последовательностей, конкатенация которых имеет восход.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 1 1 1 1 2 1 4 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 72 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, следующие $$$9$$$ последовательностей имеют восход: $$$[1, 2], [1, 2], [1, 3], [1, 3], [1, 4], [1, 4], [2, 3], [2, 4], [3, 4]$$$. Одинаковые по содержимому последовательности учитываются столько раз, сколько раз они встречаются как результат конкатенации.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'812493071e993a9b',t:'MTY5NjY2NTI0Ny45NDYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\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", "*1400"]
https://codeforces.com/blog/entry/72804
<!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="17bb3c0a988bbcfabcfbab3b80b286ce"/> <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="Hello 2020 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>Hello 2020 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='17bb3c0a988bbcfabcfbab3b80b286ce'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F72804">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='17bb3c0a988bbcfabcfbab3b80b286ce'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:37:33</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:37:33</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div><div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='17bb3c0a988bbcfabcfbab3b80b286ce'/> <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/ko_osaga">ko_osaga</a></li> <li class="current selectedLava"><a href="/blog/ko_osaga">Blog</a></li> <li><a href="/teams/with/ko_osaga">Teams</a></li> <li><a href="/submissions/ko_osaga">Submissions</a></li> <li><a href="/groups/with/ko_osaga">Groups</a></li> <li><a href="/contests/with/ko_osaga">Contests</a></li> <li><a href="/contests/writer/ko_osaga">Problemsetting</a></li> <li><a href="/streams/ko_osaga">Streams</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ko_osaga" style="text-decoration:none;color:black !important;">ko_osaga's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="73334"> <div class="title"> <a href="/blog/entry/72804"> <p>Hello 2020 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a>, <a href="/topic/73334/en12">history</a>, <span class="format-humantime" title="Jan/04/2020 18:44">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>Since the Polygon tutorial system is currently broken, I will replace the editorial with PDF format. Sorry for the inconvenience!</p><p><a href="https://www.dropbox.com/s/ysttw748rvx46eb/Hello%202020.pdf?dl=0">Solution PDF</a></p><p>Problem A was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203276">Code</a></p><p>Problem B was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203332">Code</a></p><p>Problem C was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203721">Code</a></p><p>Problem D was authored by <a class="rated-user user-orange" href="/profile/nong" title="Master nong">nong</a>. <a href="https://codeforces.com/contest/1284/submission/68203704">Code</a></p><p>Problem E was authored by <a class="rated-user user-orange" href="/profile/ckw1140" title="Master ckw1140">ckw1140</a>. <a href="https://codeforces.com/contest/1284/submission/68203754">Code</a></p><p>Problem F was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203787">Code</a></p><p>Problem G was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203817">Code</a></p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1284" class="notice" style="text-decoration: none;">Hello 2020</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-38652-73334").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "38652", blogEntryId: "72804", 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-73334"><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'>+191</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-73334"><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/ko_osaga"><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/ko_osaga"> ko_osaga </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="Jan/04/2020 18:44">4 years ago</span> </li> <li> <a href="/blog/entry/72804#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/72804#comments"> 157 </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="78289"> <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 (143)</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="570690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SHZhang" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SHZhang" title="International Grandmaster SHZhang" class="rated-user user-red">SHZhang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570690" href="?#comment-570690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570690" class="CommentVoteFrame" data-commentRating="50" data-commentUserId="1150683" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+50</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570690"> <div class="moveup"> <div class="ttypography"><p>When I open the editorial for problem E, I see the editorial for problem C instead. Can the author fix this, please?</p></div> </div> </div> <div class="reply info"> <a class="comment-570690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570690"> <li> <div class="comment"> <table class="comment-table" commentId="570700" commentParentId="570690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570700" href="?#comment-570700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570700" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570700"> <div class="moveup"> <div class="ttypography"><p>Sorry, it's fixed now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570700"> <li> <div class="comment"> <table class="comment-table" commentId="598782" commentParentId="570700"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jokerwyt" style="position: relative;"> <img src='https://userpic.codeforces.org/555567/avatar/247d0346874bdbdd.jpg'/> </a> <div><a href="/profile/jokerwyt" title="Candidate Master jokerwyt" class="rated-user user-violet">jokerwyt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/07/2020 16:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-598782" href="?#comment-598782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570700" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="598782" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555567" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-598782"> <div class="moveup"> <div class="ttypography"><p>Challenge of problem E is nice, but i have no idea how to solve it. Could you provide the solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-598782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-598782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-598782"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/21August" style="position: relative;"> <img src='https://userpic.codeforces.org/452773/avatar/13e016fa74fb3308.jpg'/> </a> <div><a href="/profile/21August" title="Master 21August" class="rated-user user-orange">21August</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570691" href="?#comment-570691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570691" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="452773" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570691"> <div class="moveup"> <div class="ttypography"><p>You got it wrong for E.</p></div> </div> </div> <div class="reply info"> <a class="comment-570691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570691"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570695" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 18:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570695" href="?#comment-570695" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570695" 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-570695"> <div class="moveup"> <div class="ttypography"><p>Really liked problems B and C :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570695"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570706" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TimonKnigge" style="position: relative;"> <img src='https://userpic.codeforces.org/275246/avatar/debe81b88ed671c2.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/TimonKnigge" title="Master TimonKnigge" class="rated-user user-orange">TimonKnigge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570706" href="?#comment-570706" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570706" class="CommentVoteFrame" data-commentRating="86" data-commentUserId="275246" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+86</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570706"> <div class="moveup"> <div class="ttypography"><p>Problem D is a lot more intuitive if you interpret the input as a collection of rectangles, where you are asked if there is a pair of rectangles that overlaps on one axis but not the other. Then a scanline solution is obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-570706 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570706 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570706"> <li> <div class="comment"> <table class="comment-table" commentId="570804" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Skeef79" style="position: relative;"> <img src='https://userpic.codeforces.org/631759/avatar/3033511aaec49179.jpg'/> </a> <div><a href="/profile/Skeef79" title="Candidate Master Skeef79" class="rated-user user-violet">Skeef79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570804" href="?#comment-570804" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570804"> <div class="moveup"> <div class="ttypography"><p>Can you please give some good resources about scanline? </p></div> </div> </div> <div class="reply info"> <a class="comment-570804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570804"> <li> <div class="comment"> <table class="comment-table" commentId="570996" commentParentId="570804"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rezwan.Arefin01" style="position: relative;"> <img src='https://userpic.codeforces.org/358701/avatar/68ec3668b1ccc552.jpg'/> </a> <div><a href="/profile/Rezwan.Arefin01" title="Candidate Master Rezwan.Arefin01" class="rated-user user-violet">Rezwan.Arefin01</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570996" href="?#comment-570996" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570804" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570996" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="358701" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570996"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.topcoder.com/community/competitive-programming/tutorials/line-sweep-algorithms/">Topcoder Tutorials</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570996 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570996 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570996"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570807" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570807" href="?#comment-570807" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570807" class="CommentVoteFrame" data-commentRating="33" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+33</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570807"> <div class="moveup"> <div class="ttypography"><p>That was the original formulation. I came up with the conference statement to make this problem much natural ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-570807 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570807 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570807"> <li> <div class="comment"> <table class="comment-table" commentId="571201" commentParentId="570807"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ghoshsai5000" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ghoshsai5000" title="Pupil ghoshsai5000" class="rated-user user-green">ghoshsai5000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571201" href="?#comment-571201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570807" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571201" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="543439" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571201"> <div class="moveup"> <div class="ttypography"><p>This was eye-opening ! So, the input format is $$$x_1, x_2, y_1, y_2$$$ and we have to look for $$$2$$$ rectangles such that their $$$x$$$-axes coincide but their $$$y$$$ do not or the other way around. </p><p>First time, we sort by $$$x$$$ and for every new line segment we process, we keep track of all the line segments it inserts with. We will check if the corresponding $$$y$$$ of the line segment fits in the bounds of all the line segments it has intersected so far. </p> <ul> <li>$$$y_1$$$ should not be greater than the smallest $$$y_2$$$ seen so far.</li> <li>$$$y_2$$$ should not be lesser than the greatest $$$y_1$$$ seen so far.</li> </ul><p>If you could include this interpretation in the editorial, it would help in understanding a lot :)</p></div> </div> </div> <div class="reply info"> <a class="comment-571201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571201"> <li> <div class="comment"> <table class="comment-table" commentId="571683" commentParentId="571201"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 19:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571683" href="?#comment-571683" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571683" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571683" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571683"> <div class="moveup"> <div class="ttypography"><p>To be honest, I think it very much depends on what you're comfortable with (Specifically, users who love geometry would love this interpretation). For me, it was easier to visualize the problem in the current format (interval format), whereas it took me a while to grasp the rectangle interpretation. It is interesting to see how the problem can be solved in so similar ways for seemingly different interpretations.</p></div> </div> </div> <div class="reply info"> <a class="comment-571683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571683"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="574189" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sthfaceless" style="position: relative;"> <img src='https://userpic.codeforces.org/1176362/avatar/4480df56f05c4612.jpg'/> </a> <div><a href="/profile/sthfaceless" title="Candidate Master sthfaceless" class="rated-user user-violet">sthfaceless</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/18/2020 20:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-574189" href="?#comment-574189" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="574189" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1176362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-574189"> <div class="moveup"> <div class="ttypography"><p>I used it too :)</p></div> </div> </div> <div class="reply info"> <a class="comment-574189 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-574189 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-574189"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570710" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Radewoosh" style="position: relative;"> <img src='https://userpic.codeforces.org/147752/avatar/a91526f3bd0194e8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570710" href="?#comment-570710" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570710" class="CommentVoteFrame" data-commentRating="76" data-commentUserId="147752" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+76</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570710"> <div class="moveup"> <div class="ttypography"><p>When will we be able to submit?</p></div> </div> </div> <div class="reply info"> <a class="comment-570710 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570710 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570710"> <li> <div class="comment"> <table class="comment-table" commentId="570734" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570734" href="?#comment-570734" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570734" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-38" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570734"> <div class="moveup"> <div class="ttypography"><p>In most contests, submission window opens 2 hours after the contest I guess.</p></div> </div> </div> <div class="reply info"> <a class="comment-570734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570734"> <li> <div class="comment"> <table class="comment-table" commentId="570808" commentParentId="570734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WaterColor2037" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/WaterColor2037" title="Master WaterColor2037" class="rated-user user-orange">WaterColor2037</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570808" href="?#comment-570808" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570808" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="876428" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570808"> <div class="moveup"> <div class="ttypography"><p>Why people downvote this?</p></div> </div> </div> <div class="reply info"> <a class="comment-570808 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570808 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570808"> <li> <div class="comment"> <table class="comment-table" commentId="570811" commentParentId="570808"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:40">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570811" href="?#comment-570811" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570808" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570811" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570811"> <div class="moveup"> <div class="ttypography"><p>Because it isn't true. Usually you can submit a few minutes after system tests are over.</p></div> </div> </div> <div class="reply info"> <a class="comment-570811 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570811 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570811"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570748" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570748" href="?#comment-570748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570748" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570748"> <div class="moveup"> <div class="ttypography"><p>Now submission is open.</p></div> </div> </div> <div class="reply info"> <a class="comment-570748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570748"> <li> <div class="comment"> <table class="comment-table" commentId="570761" commentParentId="570748"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570761" href="?#comment-570761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570748" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570761" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570761"> <div class="moveup"> <div class="ttypography"><p>Exactly 2 hours :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570711" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570711" href="?#comment-570711" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570711" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570711"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/72725?#comment-570663">Randomised sol for D</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570711 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570711 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570711"> <li> <div class="comment"> <table class="comment-table" commentId="570714" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570714" href="?#comment-570714" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570714" class="CommentVoteFrame" data-commentRating="59" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+59</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570714"> <div class="moveup"> <div class="ttypography"><p>There is another randomized approach involving hashes. You may assign random number to each lecture and then calculate for each interval the xor of numbers assigned to intervals it intersects. Now you should check that every lecture has same hashes in first and second places...</p></div> </div> </div> <div class="reply info"> <a class="comment-570714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570714"> <li> <div class="comment"> <table class="comment-table" commentId="570730" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570730" href="?#comment-570730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570730"> <div class="moveup"> <div class="ttypography"><p>how do you calculate the xor of the intersections?</p></div> </div> </div> <div class="reply info"> <a class="comment-570730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570730"> <li> <div class="comment"> <table class="comment-table" commentId="570735" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570735" href="?#comment-570735" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570735" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570735" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570735"> <div class="moveup"> <div class="ttypography"><p>I think, scan-line should work. When the interval $$$[l_i,r_i]$$$ opens, you put $$$h_i$$$ in the position $$$r_i$$$ and when this interval closes you take the xor of all numbers on the $$$[l_i, \infty)$$$.</p><p>It should look like <a href="https://ideone.com/Dypu4W">this</a>, but it gets WA-6 and I'm to sleepy to debug it properly.</p></div> </div> </div> <div class="reply info"> <a class="comment-570735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570735"> <li> <div class="comment"> <table class="comment-table" commentId="570764" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570764" href="?#comment-570764" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570764" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570764"> <div class="moveup"> <div class="ttypography"><p>yeah I did same thing but i get wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570764"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571027" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bhj2001" style="position: relative;"> <img src='https://userpic.codeforces.org/602476/avatar/71790bb4a53d93d3.jpg'/> </a> <div><a href="/profile/Bhj2001" title="Master Bhj2001" class="rated-user user-orange">Bhj2001</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571027" href="?#comment-571027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="602476" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571027"> <div class="moveup"> <div class="ttypography"><p>the WA is not because of hash collision <br /> you missed the case when 2 intervals completely overlap</p></div> </div> </div> <div class="reply info"> <a class="comment-571027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571027"> <li> <div class="comment"> <table class="comment-table" commentId="571059" commentParentId="571027"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571059" href="?#comment-571059" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571027" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571059" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571059"> <div class="moveup"> <div class="ttypography"><p>Not really, I just made a silly typo in my segment tree code... I got it accepted now: <a href="/contest/1284/submission/68205086" title="Submission 68205086 by adamant">68205086</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571059 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571059 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571059"> <li> <div class="comment"> <table class="comment-table" commentId="576198" commentParentId="571059"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anodaram" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anodaram" title="International Master anodaram" class="rated-user user-orange">anodaram</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/29/2020 08:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576198" href="?#comment-576198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571059" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576198" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="1314285" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-576198"> <div class="moveup"> <div class="ttypography"><p>Segment Tree is more popular way than multiset for this problem, I think.</p></div> </div> </div> <div class="reply info"> <a class="comment-576198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576198"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570740" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amnesiac_dusk" style="position: relative;"> <img src='https://userpic.codeforces.org/630995/avatar/5c9b8d77d7e96eff.jpg'/> </a> <div><a href="/profile/amnesiac_dusk" title="Grandmaster amnesiac_dusk" class="rated-user user-red">amnesiac_dusk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570740" href="?#comment-570740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570740" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="630995" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570740"> <div class="moveup"> <div class="ttypography"><p>It can also be treated as hashing all maximal cliques of the interval graph which should be sufficient for checking the equality of the graphs as the graph is chordal. My code for reference <a href="/contest/1284/submission/68181402" title="Submission 68181402 by amnesiac_dusk">68181402</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570740"> <li> <div class="comment"> <table class="comment-table" commentId="571137" commentParentId="570740"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tejas_919" style="position: relative;"> <img src='https://userpic.codeforces.org/875719/avatar/25f822a14baf7fbf.jpg'/> </a> <div><a href="/profile/tejas_919" title="Master tejas_919" class="rated-user user-orange">tejas_919</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571137" href="?#comment-571137" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571137" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571137"> <div class="moveup"> <div class="ttypography"><p>Can you tell me where can I learn this stuff about graphs? It would be really helpful of you.</p></div> </div> </div> <div class="reply info"> <a class="comment-571137 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571137 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571137"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570799" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/staniewzki" style="position: relative;"> <img src='https://userpic.codeforces.org/838116/avatar/307490effa9e1ae7.jpg'/> </a> <div><a href="/profile/staniewzki" title="Grandmaster staniewzki" class="rated-user user-red">staniewzki</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570799" href="?#comment-570799" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570799" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838116" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570799"> <div class="moveup"> <div class="ttypography"><p>You can look at my submission, I kept two segment trees — in one i put the value of the lecture on the beggining of the lecture and in the other on the end. Then, for each lecture i checked for lectures than do not intersect, so lectures that have end before the current beggining and the same for other side. </p></div> </div> </div> <div class="reply info"> <a class="comment-570799 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570799 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570799"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571124" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nizil" style="position: relative;"> <img src='https://userpic.codeforces.org/250190/avatar/d1314e6f3fecc96f.jpg'/> </a> <div><a href="/profile/Nizil" title="Expert Nizil" class="rated-user user-blue">Nizil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571124" href="?#comment-571124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571124" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="250190" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571124"> <div class="moveup"> <div class="ttypography"><p>I have a rather neat code doing this that might help: <a href="/contest/1284/submission/68239280" title="Submission 68239280 by Nizil">68239280</a>. I used the formula:</p> <center>$$$\{\text{Lectures that intersect lecture $$$l$$$}\} = \{\text{Lectures that start before $$$l$$$ ends}\} \setminus \{\text{Lectures that end before $$$l$$$ starts}\}$$$</center><p>. Note that if a lecture ends before $$$l$$$ starts, then it also begins before $$$l$$$ ends so in the subtraction every element of the latter set is contained in the former set. Also note that we do a XOR both when we add and when we remove a set.</p></div> </div> </div> <div class="reply info"> <a class="comment-571124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571124"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570746" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570746" href="?#comment-570746" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570746" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570746" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570746"> <div class="moveup"> <div class="ttypography"><p>My solution uses hashes also :)</p><p>Let's calculate value $$$sumA=\sum_{i \, intersects \, j}(h_i\cdot h_j)$$$ by some modulo for segments in A and the same $$$sumB$$$ for segments in B. Here, $$$h_i$$$ are some random values. This can be calculated with scanline. The answer is &quot;YES&quot; iff $$$sumA=sumB$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570746 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570746 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570746"> <li> <div class="comment"> <table class="comment-table" commentId="570766" commentParentId="570746"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570766" href="?#comment-570766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570746" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570766"> <div class="moveup"> <div class="ttypography"><p>yeah me too but i got wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570766"> <li> <div class="comment"> <table class="comment-table" commentId="570861" commentParentId="570766"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570861" href="?#comment-570861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570766" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570861"> <div class="moveup"> <div class="ttypography"><p>Maybe my code will be helpful: <a href="/contest/1284/submission/68181544" title="Submission 68181544 by VladProg">68181544</a></p><p>It doesn't use any data structures. Only two scan lines.</p></div> </div> </div> <div class="reply info"> <a class="comment-570861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570861"> <li> <div class="comment"> <table class="comment-table" commentId="570871" commentParentId="570861"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570871" href="?#comment-570871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570871"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-570871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570871"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570903" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lemelisk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lemelisk" title="Master lemelisk" class="rated-user user-orange">lemelisk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570903" href="?#comment-570903" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570903" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="513315" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570903"> <div class="moveup"> <div class="ttypography"><p>You can just treat intersections as long number in binary notification (zero means no intersection with given index's segment, one means intersection) and use its remainder as hash. See my submission <a href="https://codeforces.com/contest/1284/submission/68191562">https://codeforces.com/contest/1284/submission/68191562</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570903 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570903 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570903"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571092" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571092" href="?#comment-571092" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571092" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571092"> <div class="moveup"> <div class="ttypography"><p>I just leave it here. I also assign random number to each lecture, and then calculate some hashes. But to avoid cases when one segment completely inside in other, I just took complement approach. I get hash of all segments that doesn't intersect with selected. They are those who ends before selected, or starts after selected. So, I have two BIT for each place: one for lectures ending at time X and one for lectures starting at time X. This is done with packed coordinates and four BIT for each set of random identifiers. <a href="/contest/1284/submission/68198554" title="Submission 68198554 by r57shell">68198554</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571092 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571092 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571092"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570994" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570994" href="?#comment-570994" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570994" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570994"> <div class="moveup"> <div class="ttypography"><p>Me too.</p></div> </div> </div> <div class="reply info"> <a class="comment-570994 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570994 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570994"> <li> <div class="comment"> <table class="comment-table" commentId="570995" commentParentId="570994"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570995" href="?#comment-570995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570994" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570995"> <div class="moveup"> <div class="ttypography"><p>My randomised solution also passed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570995"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570712" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/GyojunYoun" style="position: relative;"> <img src='https://userpic.codeforces.org/227186/avatar/84d3b7d6c6ddb05c.jpg'/> </a> <div><a href="/profile/GyojunYoun" title="Grandmaster GyojunYoun" class="rated-user user-red">GyojunYoun</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570712" href="?#comment-570712" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570712" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570712" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="227186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570712"> <div class="moveup"> <div class="ttypography"><p>Thank you for setting these wonderful problems. Unlike other geometry probs, E is so beautiful that I was impressed :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570712 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570712 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570712"> <li> <div class="comment"> <table class="comment-table" commentId="570805" commentParentId="570712"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mango_lassi" style="position: relative;"> <img src='https://userpic.codeforces.org/519408/avatar/69109d1881b4b829.jpg'/> </a> <div><a href="/profile/mango_lassi" title="International Grandmaster mango_lassi" class="rated-user user-red">mango_lassi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570805" href="?#comment-570805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570712" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-29" data-commentUserId="519408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570805"> <div class="moveup"> <div class="ttypography"><p>Just what part of E do you think is beautiful? I agree that the model solution doesn't seem bad, but that is only in comparison to how painful writing code for the not-totally-magic solutions is. A problem with many easy to find ugly solutions does not turn good from the existence of a beautiful solution that is very difficult to find.</p></div> </div> </div> <div class="reply info"> <a class="comment-570805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570805"> <li> <div class="comment"> <table class="comment-table" commentId="570812" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570812" href="?#comment-570812" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570812" class="CommentVoteFrame" data-commentRating="62" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+62</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570812"> <div class="moveup"> <div class="ttypography"><p>I don't get the point. If you failed to find good solution, then it's our fault?</p></div> </div> </div> <div class="reply info"> <a class="comment-570812 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570812 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570812"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570838" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570838" href="?#comment-570838" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570838" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570838" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570838"> <div class="moveup"> <div class="ttypography"><p>Well, I found it really interesting what you can solve it in $$$O(n^2)$$$. <a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a> is really similar problem and I believe it can only be solved in $$$O(n^3)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570838 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570838 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570838"> <li> <div class="comment"> <table class="comment-table" commentId="570840" commentParentId="570838"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570840" href="?#comment-570840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570838" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570840"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-red" href="/profile/OnionPringles" title="International Grandmaster OnionPringles">OnionPringles</a> told me about the $$$O(n^2\log n)$$$ solution of that problem. Of course, it's much harder than our problem's solution, in any aspect.</p></div> </div> </div> <div class="reply info"> <a class="comment-570840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570840"> <li> <div class="comment"> <table class="comment-table" commentId="570867" commentParentId="570840"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570867" href="?#comment-570867" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570867" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570867"> <div class="moveup"> <div class="ttypography"><p>After I found $$$3x_3+4x_4+5x_5$$$ I thought I need $$$x_5$$$... After 4 TLE attempts, I saw the magic :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570867 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570867 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570867"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570722" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iaNTU" style="position: relative;"> <img src='https://userpic.codeforces.org/568681/avatar/e2c4a458dc77ff9b.jpg'/> </a> <div><a href="/profile/iaNTU" title="International Master iaNTU" class="rated-user user-orange">iaNTU</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570722" href="?#comment-570722" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570722" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-15" data-commentUserId="568681" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570722"> <div class="moveup"> <div class="ttypography"><p>Seems like you don't understand what &quot;right after&quot; means.</p></div> </div> </div> <div class="reply info"> <a class="comment-570722 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570722 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570722"> <li> <div class="comment"> <table class="comment-table" commentId="570728" commentParentId="570722"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570728" href="?#comment-570728" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570722" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570728" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-16" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570728"> <div class="moveup"> <div class="ttypography"><p>Right after systest. I'm sorry for F.</p></div> </div> </div> <div class="reply info"> <a class="comment-570728 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570728 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570728"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570739" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570739" href="?#comment-570739" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570739" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570739"> <div class="moveup"> <div class="ttypography"><p>Does the following flow solution for F run in time?</p><p>Create three sets of nodes A, B, and C. A represents the first set of edges, C represents the second set of edges. We need to match as many nodes in A as we can with nodes in C. Set B represents all the nodes in the tree. Each node in A and C will be connected to the two nodes that the edge it represents in connected to. We then run flow from the nodes in A to the nodes in C.</p><p>This graph has O(n) edges and a max flow of O(n).</p></div> </div> </div> <div class="reply info"> <a class="comment-570739 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570739 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570739"> <li> <div class="comment"> <table class="comment-table" commentId="570749" commentParentId="570739"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570749" href="?#comment-570749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570739" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570749"> <div class="moveup"> <div class="ttypography"><p>Actually, nevermind, this just doesn't work</p></div> </div> </div> <div class="reply info"> <a class="comment-570749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570749"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570743" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/snorkel" style="position: relative;"> <img src='https://userpic.codeforces.org/1360865/avatar/4aa0ab75c5725b5.jpg'/> </a> <div><a href="/profile/snorkel" title="Expert snorkel" class="rated-user user-blue">snorkel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570743" href="?#comment-570743" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360865" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570743"> <div class="moveup"> <div class="ttypography"><p>When the codes will be available?</p></div> </div> </div> <div class="reply info"> <a class="comment-570743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570743"> <li> <div class="comment"> <table class="comment-table" commentId="570767" commentParentId="570743"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570767" href="?#comment-570767" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570743" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570767" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570767"> <div class="moveup"> <div class="ttypography"><p>Code is available now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570767"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570750" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570750" href="?#comment-570750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570750" class="CommentVoteFrame" data-commentRating="12" 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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570750"> <div class="moveup"> <div class="ttypography"><p>For F we can prove that answer always equals $$$n - 1$$$ easily using Hall theorem. Pick any $$$k$$$ edges in first tree, we want to prove that there are at least $$$k$$$ edges in the second tree which can be used to replace at least one of picked edges. Let's remove all picked edges from the tree, then it splits to $$$k + 1$$$ components. For each edge in the second tree let's draw an edge between components containing endpoints of the edge. Since the tree was connected before compressing edges it is still connected now, which means it has at least $$$k$$$ edges which are not self-loops, which means there are at least $$$k$$$ edges which can be used to replace one of picked edges.</p></div> </div> </div> <div class="reply info"> <a class="comment-570750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570750"> <li> <div class="comment"> <table class="comment-table" commentId="570752" commentParentId="570750"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 19:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570752" href="?#comment-570752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570750" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570752" 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-570752"> <div class="moveup"> <div class="ttypography"><p>Sadly this proof gives no clue on how to find the matching</p></div> </div> </div> <div class="reply info"> <a class="comment-570752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570752"> <li> <div class="comment"> <table class="comment-table" commentId="570774" commentParentId="570752"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570774" href="?#comment-570774" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570774" 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-570774"> <div class="moveup"> <div class="ttypography"><p>In my solution (tl;dr <a href="https://codeforces.com/blog/entry/72725?#comment-570604">here</a>), it just turns out while I'm looking for some characteristics of the matching that it is perfect, and the argument for that is kinda similar to Hall's theorem — it also deals with sets of edges in T2 and adjacent edges in T1. It doesn't seem to be particularly useful for finding a way to compute a matching quickly, though.</p></div> </div> </div> <div class="reply info"> <a class="comment-570774 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570774 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570774"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570772" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570772" href="?#comment-570772" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570772" class="CommentVoteFrame" data-commentRating="20" 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;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570772"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p><p>Pick a 1 edge (u, v) from the T1, s.t. u is the leaf in T1. We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A). We can find matching, (u, v) in T1 &amp; (u, w) in T2, and remove those edges. For all x($$$x \neq w$$$), if there is a edge (u, x) in T2, we change u to v. it means, remove (u, x) and add(v, x) (step B). As a result, we can remove vertexes u and reduce problem size by one(after operate, T2 remained as tree).</p><p>How to simulate? Bottleneck is the step B, changing (u, x) to (v, x). Therefore we don't change all edges, but simply remove (u, w) and add dummy edge (u, v). We have to find nearest non-dummy edge in step A, but it's all. We can easily do it by Link-Cut Tree</p></div> </div> </div> <div class="reply info"> <a class="comment-570772 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570772 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570772"> <li> <div class="comment"> <table class="comment-table" commentId="570782" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570782" href="?#comment-570782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570782" 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-570782"> <div class="moveup"> <div class="ttypography"><blockquote><p>We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A).</p> </blockquote><p>Tbh when you have this, there's no need for further tricks or LCT. Just HLD over T1, store not yet taken edges in each path in a set (ordered by depth), DFS over T2 and use HLD to simulate the process for each edge in T2. That's my solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-570782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570782"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570785" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OnionPringles" 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/OnionPringles" title="International Grandmaster OnionPringles" class="rated-user user-red">OnionPringles</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570785" href="?#comment-570785" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570785" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="360543" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570785"> <div class="moveup"> <div class="ttypography"><p>I solved step B by merging u,v in T2 by implementing union-find structure on LCT nodes. When merging u and v, cut all preferred children of u and v so that the children can go through union-find structure when they try to access the unpreferred parent. I think it is easy if you have a pre-written LCT code.</p></div> </div> </div> <div class="reply info"> <a class="comment-570785 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570785 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570785"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570791" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gamegame" style="position: relative;"> <img src='https://userpic.codeforces.org/352372/avatar/8717a5b44702348a.jpg'/> </a> <div><a href="/profile/gamegame" title="Legendary Grandmaster gamegame" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>amegame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570791" href="?#comment-570791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="352372" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570791"> <div class="moveup"> <div class="ttypography"><p>You can do binary lifting and dsu, which is much more easier to code than LCT/HLD</p></div> </div> </div> <div class="reply info"> <a class="comment-570791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570791"> <li> <div class="comment"> <table class="comment-table" commentId="571082" commentParentId="570791"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 12:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571082" href="?#comment-571082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570791" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571082" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571082"> <div class="moveup"> <div class="ttypography"><p>I had the same, but tbh in such contests it would be more preferable to just copy LCT.</p></div> </div> </div> <div class="reply info"> <a class="comment-571082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571082"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570884" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570884" href="?#comment-570884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570884" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570884"> <div class="moveup"> <div class="ttypography"><p>I updated my solution to F. It is my favorite in this problem set. Hope you liked it too!</p></div> </div> </div> <div class="reply info"> <a class="comment-570884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570884"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570783" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570783" href="?#comment-570783" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570783" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+61</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570783"> <div class="moveup"> <div class="ttypography"><p>Here is a more intuitive explanation for E. Sorry if it's mentioned already.</p><p>Fix the point $$$p$$$. Translate everything such that $$$p$$$ coincides with the origin. Sort all the other points counter-clockwise. We shall now find the number of quadruples of points that <em>don't</em> form a polygon containing $$$p$$$.</p><p>Now consider some point $$$s$$$. Consider the half-plane $$$H$$$ of points $$$t$$$ such that the cross product $$$s \wedge t$$$ is positive. For a quadrilateral with $$$s$$$ to contain $$$p$$$, it has to have at least one point from $$$H$$$ and at least one point not from $$$H$$$. Conversely, we will count the number of quadruples $$$(s, t_1, t_2, t_3)$$$ such that $$$t_1, t_2, t_3 \in H$$$. It is just the binomial coefficient $$$|H| \choose 3$$$.</p><p>Now do that for all $$$s$$$ and all corresponding $$$H$$$, in linear time, using the two pointers method.</p><p>With iterating over all $$$p$$$ and sorting, the complexity is $$$O (n^2 \log n)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570783 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570783 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570783"> <li> <div class="comment"> <table class="comment-table" commentId="571005" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLamarca" style="position: relative;"> <img src='https://userpic.codeforces.org/379329/avatar/842836a6a188aadb.jpg'/> </a> <div><a href="/profile/VLamarca" title="Master VLamarca" class="rated-user user-orange">VLamarca</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571005" href="?#comment-571005" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571005" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571005" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="379329" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571005"> <div class="moveup"> <div class="ttypography"><p>This solution works for any size of polygon right? For example if the problem was about triangles instead of quadrilaterals</p><p>thanks for sharing it btw </p></div> </div> </div> <div class="reply info"> <a class="comment-571005 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571005 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571005"> <li> <div class="comment"> <table class="comment-table" commentId="571175" commentParentId="571005"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571175" href="?#comment-571175" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571005" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571175" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571175"> <div class="moveup"> <div class="ttypography"><p>Looks like, yeah, the same argument about all points being in one half-plane would work for pentagons and more.</p><p>Now, if the problem asks for <em>convex</em> polygons, it gets trickier, even with quadrilaterals.</p></div> </div> </div> <div class="reply info"> <a class="comment-571175 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571175 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571175"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571064" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Simurgh" style="position: relative;"> <img src='https://userpic.codeforces.org/1365761/avatar/1d3d3be9bd64e4c9.jpg'/> </a> <div><a href="/profile/Simurgh" title="Expert Simurgh" class="rated-user user-blue">Simurgh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571064" href="?#comment-571064" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571064" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1365761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571064"> <div class="moveup"> <div class="ttypography"><p>Where can I learn more about cross products of vectors and how they can be used in geometry problems?</p></div> </div> </div> <div class="reply info"> <a class="comment-571064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571064"> <li> <div class="comment"> <table class="comment-table" commentId="571178" commentParentId="571064"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571178" href="?#comment-571178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571064" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571178"> <div class="moveup"> <div class="ttypography"><p>Basically, scalar product and cross product are similar in behavior to cosine and sine of angle between vectors, respectively. Their signs behave the same.</p><p>The upside is that, more often than not, we are given coordinates of points as integers (or rationals). And computing scalar and cross products can be done using integers only. So we don't have to resort to floating point and then deal with a whole additional class of errors because of loss of precision.</p><p>As for more general overview, a <a href="https://www.google.com/search?q=scalar+product+and+cross+product+in+computational+geometry">Google search</a> lands some nice articles on the first page.</p></div> </div> </div> <div class="reply info"> <a class="comment-571178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571178"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571093" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 13:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571093" href="?#comment-571093" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571093" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571093" class="CommentVoteFrame" data-commentRating="10" 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: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-571093"> <div class="moveup"> <div class="ttypography"><p>How can I actually easily find the sign of the cross product between two vectors? I got an idea of how to do it with the angle between them, but it seems ugly and probably prone to bugs.</p><p>Edit: I found a way on <a href="https://en.wikipedia.org/wiki/Cross_product#Computational_geometry">Wikipedia</a>, scroll down to the Computation Geometry section.</p></div> </div> </div> <div class="reply info"> <a class="comment-571093 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571093 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571093"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570787" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/undisputedAshu" style="position: relative;"> <img src='https://userpic.codeforces.org/327726/avatar/92b4b2153c6ba4e4.jpg'/> </a> <div><a href="/profile/undisputedAshu" title="Pupil undisputedAshu" class="rated-user user-green">undisputedAshu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570787" href="?#comment-570787" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570787" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="327726" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570787"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain for B</p><p>3</p><p>4 2 0 2 0</p><p>6 9 9 8 8 7 7</p><p>1 6</p><p>how is it 7?</p></div> </div> </div> <div class="reply info"> <a class="comment-570787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570787"> <li> <div class="comment"> <table class="comment-table" commentId="570793" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/djm03178" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/djm03178" title="Master djm03178" class="rated-user user-orange">djm03178</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570793" href="?#comment-570793" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570793" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="687688" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570793"> <div class="moveup"> <div class="ttypography"><p>Let's say a = [2,0,2,0], b = [9,9,8,8,7,7], c = [6], then the answers are: aa, ab, ac, ba, bb, ca, and cb.</p></div> </div> </div> <div class="reply info"> <a class="comment-570793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570793"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570794" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gol_en_05" style="position: relative;"> <img src='https://userpic.codeforces.org/838032/avatar/8167074e5c48a57d.jpg'/> </a> <div><a href="/profile/gol_en_05" title="Specialist gol_en_05" class="rated-user user-cyan">gol_en_05</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570794" href="?#comment-570794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570794" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570794"> <div class="moveup"> <div class="ttypography"><p>since 2 0 2 0 has an ascent.so total pairs are 3. 2 nd sequence does not have an ascent but pairs (2,2),(2,1) has ascent. similarly for 3rd sequence pairs(3,1) and(3,2) has ascent. so total 7 pairs are possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-570794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570794"> <li> <div class="comment"> <table class="comment-table" commentId="570904" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570904" href="?#comment-570904" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570904" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570904"> <div class="moveup"> <div class="ttypography"><p>I'm struggling to understand what does &quot;but pairs (2,2),(2,1) has ascent&quot; mean. Can you please elaborate? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-570904 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570904 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570904"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570916" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570916" href="?#comment-570916" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570916" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570916"> <div class="moveup"> <div class="ttypography"><p>Thanks I got it!</p></div> </div> </div> <div class="reply info"> <a class="comment-570916 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570916 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570916"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570795" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BOGDAN_" 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/BOGDAN_" title="Expert BOGDAN_" class="rated-user user-blue">BOGDAN_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570795" href="?#comment-570795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570795" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="635882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570795"> <div class="moveup"> <div class="ttypography"><p>Let 1, 2, 3 — indexes of arrays. Here is &quot;1 + 2&quot;</p><p>&quot;1 + 3&quot;</p><p>&quot;1 + 1&quot;</p><p>&quot;2 + 2&quot;</p><p>&quot;2 + 1&quot;</p><p>&quot;3 + 1&quot;</p><p>&quot;3 + 2&quot;</p><p>At all — answer 7.</p></div> </div> </div> <div class="reply info"> <a class="comment-570795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570803" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Wa-Automaton" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Wa-Automaton" title="Candidate Master Wa-Automaton" class="rated-user user-violet">Wa-Automaton</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570803" href="?#comment-570803" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570803" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570803" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1365147" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570803"> <div class="moveup"> <div class="ttypography"><p>For D, removing operation is at time ea_i + 1 ?</p><p>UPD: It's fixed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570803 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570803 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570803"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570816" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570816" href="?#comment-570816" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570816" 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="570816" 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-570816"> <div class="moveup"> <div class="ttypography"><p>D can be solved using &quot;Job scheduling &quot; algorithm. Initially we check all the intervals for both the venues individually,whether they overlap,if we get different answer,answer is &quot;NO&quot;.</p><p>If we get same answer and both timings of both venues don't overlap,then answer is &quot;YES&quot;.</p><p>If we get &quot;over-lap&quot; for both,there is a possibility that removing some lectures might make one venue overlapping and other non_overlapping</p><p>eg: 1 2 3 4</p> <pre>3 4 4 5 4 5 6 7</pre><p>In this case,we use job scheduling algorithm to find the largest no of lectures that can be present such that,lecture timings don't overlap for venue A.</p><p>Keep only those lectures for B,check if answer is different for both venues,do the same thing for venue B.</p><p><a href="/contest/1284/submission/68206806" title="Submission 68206806 by AjaySabarish">68206806</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570816 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570816 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570816"> <li> <div class="comment"> <table class="comment-table" commentId="571060" commentParentId="570816"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571060" href="?#comment-571060" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570816" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571060" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571060"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/AjaySabarish" title="Expert AjaySabarish">AjaySabarish</a> Hi, can you please explain the part about &quot;non over-lap&quot; in a little detail?How is there a possibility that removing some lectures might make one venue overlapping and other non_overlapping? I also thought about job scheduling algo but as mentioned in comments, did not consider such cases like finding interval in a and then checking them in b and vice versa. Do they both not give same result? </p></div> </div> </div> <div class="reply info"> <a class="comment-571060 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571060 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571060"> <li> <div class="comment"> <table class="comment-table" commentId="571066" commentParentId="571060"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 11:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571066" href="?#comment-571066" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571060" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571066" 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-571066"> <div class="moveup"> <div class="ttypography"><p>Sry there was a typo,now corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-571066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571066"> <li> <div class="comment"> <table class="comment-table" commentId="571198" commentParentId="571066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571198" href="?#comment-571198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571198"> <div class="moveup"> <div class="ttypography"><p>Still can you explain that point about removing some lectures?</p></div> </div> </div> <div class="reply info"> <a class="comment-571198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571198"> <li> <div class="comment"> <table class="comment-table" commentId="571219" commentParentId="571198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571219" href="?#comment-571219" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571219" 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-571219"> <div class="moveup"> <div class="ttypography"><p>Consider the above example,which I gave </p><p>3</p><p>1 2 3 4</p><p>3 4 4 5</p><p>4 5 6 7</p><p>Now,the timings overlap for both venues,but if you remove lecture 3,timings dont overlap for venue A but overlap for venue B.</p><p>This is the last case which I was talking about,now you have to use job scheduling to find the answer.</p><p>Find the highest number of non overlapping segments for A,it is lecture 1,2.</p><p>Now keep only these lectures for both venues,now the segments for B should also not overlap for &quot;not venue sensitive&quot;. But it is overlapping,so it is venue sensitive</p></div> </div> </div> <div class="reply info"> <a class="comment-571219 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571219 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571219"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570825" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SajidZakaria" style="position: relative;"> <img src='https://userpic.codeforces.org/553136/avatar/f6d8cc00ec65b842.jpg'/> </a> <div><a href="/profile/SajidZakaria" title="Candidate Master SajidZakaria" class="rated-user user-violet">SajidZakaria</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570825" href="?#comment-570825" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570825" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="553136" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570825"> <div class="moveup"> <div class="ttypography"><p>The test cases in D were very &quot;weak&quot;. My solution : <a href="/contest/1284/submission/68205621" title="Submission 68205621 by SajidZakaria">68205621</a></p><p>For very large N, it's enough to only check if each of the lectures have the same number of intersections in A and B. Taking advantage of the fact that it's hard to put up a test case that avoids being fooled that way.</p></div> </div> </div> <div class="reply info"> <a class="comment-570825 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570825 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570825"> <li> <div class="comment"> <table class="comment-table" commentId="634898" commentParentId="570825"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Prajwal_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Prajwal_" title="Expert Prajwal_" class="rated-user user-blue">Prajwal_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/02/2020 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-634898" href="?#comment-634898" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570825" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="634898" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360518" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-634898"> <div class="moveup"> <div class="ttypography"><p>but how will you calculate the intersections in O(n) time.Can you explain once more??</p></div> </div> </div> <div class="reply info"> <a class="comment-634898 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-634898 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-634898"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570829" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570829" href="?#comment-570829" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570829" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570829"> <div class="moveup"> <div class="ttypography"><p>Can you share other solutions to E? Except <a class="rated-user user-orange" href="/profile/Gassa" title="International Master Gassa">Gassa</a>'s (above)</p></div> </div> </div> <div class="reply info"> <a class="comment-570829 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570829 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570829"> <li> <div class="comment"> <table class="comment-table" commentId="570852" commentParentId="570829"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570852" href="?#comment-570852" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570829" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570852" 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="570852" class="CommentVoteFrame" data-commentRating="45" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+45</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570852"> <div class="moveup"> <div class="ttypography"><p>I'll put it short:</p> <ul> <li>(By <a class="rated-user user-red" href="/profile/kdh9949" title="International Grandmaster kdh9949">kdh9949</a> <a class="rated-user user-orange" href="/profile/jihoon" title="International Master jihoon">jihoon</a>) Find $$$f(p)$$$ for each point. You can see that the set can enclose $$$p$$$ iff its convex hull contains $$$p$$$. Checking the containment is hard, so sort by angle, and eliminate the set that does not contain $$$p$$$, which reduces to almost similar sweep with model code. I think this is the easiest solution to come up with.</li> <li>(By <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a>) The answer depends on the 2 * (number of convex quadrilaterals) + (number of concave quadrilaterals). We denote this number $$$A$$$. I think the answer is $$$(A - 2\binom{n}{4}) \times (n-4)/2$$$, or something like that. This problem is bit harder, so you need another type of angular sweep like JOI Open 2017 Bulldozer. I think this is more involved to code, but our great tester <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a> took exactly 12 minutes to AC this.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-570852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570852"> <li> <div class="comment"> <table class="comment-table" commentId="571006" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/NoLongerRed" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/NoLongerRed" title="Grandmaster NoLongerRed" class="rated-user user-red">NoLongerRed</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571006" href="?#comment-571006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571006" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="567645" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571006"> <div class="moveup"> <div class="ttypography"><p>My solution is pretty much the same as molamola's solution and I think it is not necessary to do a cool angular sweep:<br />Let $$$X$$$ be the number of $$$((A,B,C),D)$$$ such that $$$D$$$ lies in $$$ABC$$$ and $$$(A,B,C)$$$ is an unordered tuple. The answer is $$$(n-4)X/2$$$.<br />$$$X$$$ can be counted easily: fixing $$$D$$$ and sort other points by the angles, then do a bunch of lower bound.</p></div> </div> </div> <div class="reply info"> <a class="comment-571006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571006"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571012" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571012" href="?#comment-571012" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571012" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571012"> <div class="moveup"> <div class="ttypography"><p>Thanks for sharing. The solution in Editorial really beautiful, but I don't know. Is that possible to came up with such solution in ~1 hour?</p></div> </div> </div> <div class="reply info"> <a class="comment-571012 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571012 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571012"> <li> <div class="comment"> <table class="comment-table" commentId="571014" commentParentId="571012"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571014" href="?#comment-571014" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571012" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571014" 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="571014" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571014"> <div class="moveup"> <div class="ttypography"><p>Actually my solution submitted during the contest is exactly same as the tutorial solution. In fact, I tried to compute all of $$$x$$$, $$$y$$$, and $$$z$$$, so I double-counted not only the edges of the convex hull but also the diagonal edges, to obtain three linear equations.</p> <center>$$$ x + y + z = {n \choose 5} \\ 5x + 4y + 3z = sth \\ 5x + 6y + 7z = sth $$$</center><p>Unfortunately, this linear system was undetermined, and all I can get was $$$(y + 2z)$$$. That was when I felt quite disappointed. But surprisingly, the answer to the problem happened to be exactly $$$(y + 2z)$$$, so I could finally solve the problem.</p><p>At first, I thought I was lucky enough to find a solution with such unsolvable system. So I headed to this tutorial to read the &quot;official&quot; solution, only to find my solution again. Thanks to your question, I found it in the comments :-)</p><p><a href="/contest/1284/submission/68196878" title="Submission 68196878 by jo_on">68196878</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571014 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571014 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571014"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570830" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570830" href="?#comment-570830" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570830" class="CommentVoteFrame" data-commentRating="3" 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: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-570830"> <div class="moveup"> <div class="ttypography"><p>Just curious,did everyone who solved C in contest,prove the solution?It was not so obvious to me,deciphering and processing what a &quot;framed segment&quot; is,took a lot of time.</p><p>Finding pattern was quite difficult,as manually generating test case even for n=4 is difficult</p><p>Lot of people solved it,is there any other idea?</p></div> </div> </div> <div class="reply info"> <a class="comment-570830 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570830 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570830"> <li> <div class="comment"> <table class="comment-table" commentId="570899" commentParentId="570830"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570899" href="?#comment-570899" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570830" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570899" class="CommentVoteFrame" data-commentRating="2" 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:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570899"> <div class="moveup"> <div class="ttypography"><p>Hi, If you now know what a &quot;framed segment&quot; is, then try to formulate number of &quot;framed segment&quot; of a particular length for a given n. For example: if we want to count &quot;framed segement&quot; of length 1. Let's first consider all &quot;framed segment&quot; containing only digit 1. For this &quot;framed segment&quot; to be at leftmost, there are (n — 1)! permutations. Similar argument goes for its other positions as well. This gives us count : (n — 1)! * n. Now, there are total of n single digits like &quot;1&quot; which can make single length &quot;framed segement&quot;. Thus now count for all single length &quot;framed segement&quot; is : (n — 1)! * n * n (something missing?). I have tried to explain the solution with single length fragment above with some details missing which I think you will figure out. Please try to come-up with a general formulation for any &quot;framed segment&quot;length x for a given n. Summing it all up will give you the answer. Link to my submission : <a href="https://codeforces.com/contest/1284/submission/68187501">Here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570899 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570899 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570899"> <li> <div class="comment"> <table class="comment-table" commentId="570912" commentParentId="570899"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570912" href="?#comment-570912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570899" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570912" 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-570912"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot,I get the solution,but I am just curious about the high number of submissions,was it so obvious?did everyone actually prove it or used their intuition to get it?</p></div> </div> </div> <div class="reply info"> <a class="comment-570912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570912"> <li> <div class="comment"> <table class="comment-table" commentId="570917" commentParentId="570912"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570917" href="?#comment-570917" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570912" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570917" 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-570917"> <div class="moveup"> <div class="ttypography"><p>I guess that depends on one's way of counting up to the answer. And from the number of submissions, it feels like people are actually good at counting..:P</p></div> </div> </div> <div class="reply info"> <a class="comment-570917 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570917 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570917"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kiimak" style="position: relative;"> <img src='https://userpic.codeforces.org/780779/avatar/9d6b81e1dd625cd6.jpg'/> </a> <div><a href="/profile/kiimak" title="Candidate Master kiimak" class="rated-user user-violet">kiimak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570849" href="?#comment-570849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570849" 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="570849" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="780779" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570849"> <div class="moveup"> <div class="ttypography"><p>Hi, I think I found a test case for problem D where my solution gets accepted but it should be incorrect.</p> <pre><code>5 1 10 1 10 2 20 11 30 11 30 2 20 21 40 21 40 31 50 31 50 </code></pre><p>I've checked with the code given in the tutorial, the answer is NO, but my solution gives YES. <a href="/contest/1284/submission/68207409" title="Submission 68207409 by kiimak">68207409</a></p><p>I've modeled it as a graph and put an edge (u, v) if lecture u and v meet. I thought it would be enough to check two things for graph A and B (venue A and B)</p> <ul> <li>the number of degrees for each lecture</li> <li>the lecture set of each component</li> </ul><p>I've submitted it after the contest so it doesn't effect my ratings, but I thought it was worth mentioning.</p></div> </div> </div> <div class="reply info"> <a class="comment-570849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570849"> <li> <div class="comment"> <table class="comment-table" commentId="570891" commentParentId="570849"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ormlis" style="position: relative;"> <img src='https://userpic.codeforces.org/1250517/avatar/5b32008c179f4f98.jpg'/> </a> <div><a href="/profile/Ormlis" title="Legendary Grandmaster Ormlis" class="rated-user user-legendary"><span class="legendary-user-first-letter">O</span>rmlis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570891" href="?#comment-570891" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570891" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1250517" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570891"> <div class="moveup"> <div class="ttypography"><p>I made the same mistake. I tried to find a test case where this is not true, but I could not. Thanks you</p></div> </div> </div> <div class="reply info"> <a class="comment-570891 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570891 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570891"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DJoker99" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/DJoker99" title="Pupil DJoker99" class="rated-user user-green">DJoker99</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570865" href="?#comment-570865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570865" 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="570865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="886083" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570865"> <div class="moveup"> <div class="ttypography"><p>Solution for B [Best :- O(n) Worst :- O(nlogn)]</p><p><a href="https://codeforces.com/contest/1284/submission/68210022">https://codeforces.com/contest/1284/submission/68210022</a></p><p>The condition for a non-ascent sequence a and a non-ascen sequence b to form an ascenting sequence is</p><p><code>min(a) &lt;max(b)</code></p> <ol> <li>First traverse the lists and store max and min in two separate vectors.</li> <li>if a sequence has ascent ie if an element greater than current min or current max occurs then that sequence will always give an ascenting sequence hence do <code>cnt = cnt + 2*n-1</code> <code>n--;</code> because that sequence will form 2n-1 sequences on concatenation</li> <li><p>Sort the max and min vectors then use two pointer approach.</p></li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-570865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570865"> <li> <div class="comment"> <table class="comment-table" commentId="570973" commentParentId="570865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 00:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570973" href="?#comment-570973" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570865" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570973" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570973" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570973"> <div class="moveup"> <div class="ttypography"><p>Involving sort gives already nlogn solution) - <a href="https://codeforces.com/contest/1284/submission/68206308">my code</a> — P. S. I have similar solution, but simpler.</p></div> </div> </div> <div class="reply info"> <a class="comment-570973 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570973 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570973"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570877" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prateek_aries" style="position: relative;"> <img src='https://userpic.codeforces.org/780171/avatar/c6136d0edef16466.jpg'/> </a> <div><a href="/profile/prateek_aries" title="Expert prateek_aries" class="rated-user user-blue">prateek_aries</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570877" href="?#comment-570877" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570877" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="780171" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570877"> <div class="moveup"> <div class="ttypography"><p>Someone please explain me the meaning of the last statement in C. &quot;By observing that there exist exactly n−len+1 pairs with 1≤l≤r≤n,r−l+1=len, we can simply multiply this number for each length, giving a O(n) time solution.&quot; Please give any example.</p></div> </div> </div> <div class="reply info"> <a class="comment-570877 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570877 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570877"> <li> <div class="comment"> <table class="comment-table" commentId="570981" commentParentId="570877"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570981" href="?#comment-570981" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570877" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570981" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570981"> <div class="moveup"> <div class="ttypography"><p>Example of what is it about: </p><p>Consider n of 5 and len of 3</p> <ul> <li><p>1 2 3</p></li> <li><p>2 3 4</p></li> <li><p>3 4 5</p></li> </ul><p>Permutate each of them, and you will get all framed subarrays for n and len of the example. </p></div> </div> </div> <div class="reply info"> <a class="comment-570981 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570981 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570981"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570883" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/im_sanyam" style="position: relative;"> <img src='https://userpic.codeforces.org/605247/avatar/6943d67eaf1d4243.jpg'/> </a> <div><a href="/profile/im_sanyam" title="Expert im_sanyam" class="rated-user user-blue">im_sanyam</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570883" href="?#comment-570883" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570883" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="605247" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570883"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain to me the solution of problem C in a better and intuitive way?</p></div> </div> </div> <div class="reply info"> <a class="comment-570883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570883"> <li> <div class="comment"> <table class="comment-table" commentId="570902" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570902" href="?#comment-570902" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570902" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570902" 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-570902"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570902 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570902 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570902"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570911" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/meiniak" style="position: relative;"> <img src='https://userpic.codeforces.org/803808/avatar/924fee722719da18.jpg'/> </a> <div><a href="/profile/meiniak" title="Newbie meiniak" class="rated-user user-gray">meiniak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570911" href="?#comment-570911" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570911" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="803808" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570911"> <div class="moveup"> <div class="ttypography"><p>let's take n = 5. ar = [1,2,3,4,5] . Now iterate for all possible length of sub-array and count number of good sub-array for that length. k = 1, 2, 3 and so on.</p><p>let take say k = 2 and n = 5. So there are n-k+1 position possible to place k elements i.e If we consider [1,2] then we can place [1,2] in position _ 3 _ 4 _ 5 _ and you can select (n-k+1) elements from n elements to i.e [1,2] , [2,3] , [3,4] and [4,5] . So this is how we got (n-k+1) * (n-k+1) and now we just have to count number of possible permutation of k and (n-k) elements left which is nothing but k! and (n-k)! .** (n-k+1) * (n-k+1) * k! * (n-k)!** is the total answer</p></div> </div> </div> <div class="reply info"> <a class="comment-570911 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570911 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570911"> <li> <div class="comment"> <table class="comment-table" commentId="647624" commentParentId="570911"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lazy_learner" style="position: relative;"> <img src='https://userpic.codeforces.org/926934/avatar/1c97e4ddf06e9813.jpg'/> </a> <div><a href="/profile/lazy_learner" title="Newbie lazy_learner" class="rated-user user-gray">lazy_learner</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2020 08:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-647624" href="?#comment-647624" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570911" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="647624" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926934" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-647624"> <div class="moveup"> <div class="ttypography"><p>But would that not lead to overcounting.<br />Consider the case 3 (1 2) 4 5 and 3 1 2 (4 5).<br />These 2 permutations are same and will be counted twice, once when we consider 1,2 together and second when 4,5 are taken together.</p></div> </div> </div> <div class="reply info"> <a class="comment-647624 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-647624 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-647624"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570914" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rover1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rover1" title="Specialist rover1" class="rated-user user-cyan">rover1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570914" href="?#comment-570914" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570914" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1239447" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570914"> <div class="moveup"> <div class="ttypography"><p>If in question C, we have given a permutation of length n then we need to find happiness... Anyone want to share their approaches ..</p></div> </div> </div> <div class="reply info"> <a class="comment-570914 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570914 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570914"> <li> <div class="comment"> <table class="comment-table" commentId="570918" commentParentId="570914"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570918" href="?#comment-570918" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570914" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570918" 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-570918"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570918"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570927" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/M1v1savva1601" style="position: relative;"> <img src='https://userpic.codeforces.org/539005/avatar/21949389dc808e09.jpg'/> </a> <div><a href="/profile/M1v1savva1601" title="Master M1v1savva1601" class="rated-user user-orange">M1v1savva1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570927" href="?#comment-570927" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570927" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="539005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570927"> <div class="moveup"> <div class="ttypography"><p>Shouldn't it be <strong>eai + 1</strong> in D tutorial?</p></div> </div> </div> <div class="reply info"> <a class="comment-570927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570927"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570941" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AwakeAnay" style="position: relative;"> <img src='https://userpic.codeforces.org/666008/avatar/7043fde46ee0493c.jpg'/> </a> <div><a href="/profile/AwakeAnay" title="Grandmaster AwakeAnay" class="rated-user user-red">AwakeAnay</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 23:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570941" href="?#comment-570941" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="666008" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570941"> <div class="moveup"> <div class="ttypography"><p>I had a overkill solution for $$$D$$$ which led to a good data structures problem. While, others have provided much more elegant solutions, this reduced version is a good problem on its own and worth sharing.</p><p>Here's the problem:</p><p>You are given two sequences $$$a_i$$$ and $$$b_i$$$ of length $$$2N$$$ each. Each number from $$$1$$$ to $$$N$$$ appears exactly twice in both the sequences. You have to solve $$$Q$$$ queries of the following kind:</p><p>Given $$$l$$$, $$$r$$$, $$$x$$$ and $$$y$$$, find the set of distinct elements in $$$(l, r)$$$ in $$$a$$$ is exactly equal to the set of distinct elements in $$$(x, y)$$$ in $$$b$$$. That is, any number $$$u$$$ has an appearance in segment $$$(l, r)$$$ in $$$a$$$ if and only if it has an appearance in segment $$$(x, y)$$$ in $$$b$$$. Try to solve this online in $$$O((N+Q)\log(N))$$$.</p><p>Think of how you can reduce today's $$$D$$$ into this problem.</p><p>My code for today's D: <a href="/contest/1284/submission/68189310" title="Submission 68189310 by AwakeAnay">68189310</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570941"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570975" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/madhav_1999" style="position: relative;"> <img src='https://userpic.codeforces.org/594602/avatar/cad96e04d2a42e66.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/madhav_1999" title="Master madhav_1999" class="rated-user user-orange">madhav_1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570975" href="?#comment-570975" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570975" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="594602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570975"> <div class="moveup"> <div class="ttypography"><p>In D: &quot;Event removing interval [sbi, ebi] from S at time ebi+1.&quot;</p><p><a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a>, I think you made an error here, it should be eai + 1 instead</p></div> </div> </div> <div class="reply info"> <a class="comment-570975 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570975 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570975"> <li> <div class="comment"> <table class="comment-table" commentId="571032" commentParentId="570975"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571032" href="?#comment-571032" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570975" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571032" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571032"> <div class="moveup"> <div class="ttypography"><p>Sorry, fixed. </p></div> </div> </div> <div class="reply info"> <a class="comment-571032 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571032 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571032"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570982" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 02:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570982" href="?#comment-570982" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570982" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570982"> <div class="moveup"> <div class="ttypography"><p>Problem B can also be solved in $$$O(n)$$$. Be $$$asc$$$ the number of sequences that have an ascent. For each sequence, check if it's non-increasing. If it isn't any concatenation we do will have an ascent, so we can add $$$n$$$ to our answer and $$$1$$$ to $$$asc$$$. Now be $$$s$$$ a non-increasing sequence and let's set it as the right part of the concatenation. We will only have an ascent in the concatenation if the left part already has an ascent or has an element smaller than any element in $$$s$$$, specially it's maximum. We have $$$asc$$$ sequences of the first type, so that's easy, and for the second part we can precalculate it by creating an array $$$minfreq$$$ where we store the minimum of each non-increasing sequence in it's position (as $$$s_{i,j} &lt; 10^6$$$) and do a sweep from $$$1$$$ to $$$10^6$$$ to accumulate our sum ($$$minfreq[i] = minfreq[i-1] +minfreq[i]$$$). Now we have our answer for the second part in position $$$minfreq[max(s)-1]$$$, and we can just add both parts to our answer. Since we can precalculate $$$minfreq$$$, $$$max(s)$$$ and $$$asc$$$ in $$$O(n)$$$ and the answer can be calculated in $$$O(1)$$$ using our precalculations total complexity is $$$O(n)$$$ </p></div> </div> </div> <div class="reply info"> <a class="comment-570982 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570982 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570982"> <li> <div class="comment"> <table class="comment-table" commentId="570987" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dblark" style="position: relative;"> <img src='https://userpic.codeforces.org/693276/avatar/70323ef41e4c9add.jpg'/> </a> <div><a href="/profile/dblark" title="International Master dblark" class="rated-user user-orange">dblark</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 03:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570987" href="?#comment-570987" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570987" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="693276" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570987"> <div class="moveup"> <div class="ttypography"><p>Yeah, the same idea with you!</p></div> </div> </div> <div class="reply info"> <a class="comment-570987 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570987 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570987"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571037" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 08:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571037" href="?#comment-571037" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571037" class="CommentVoteFrame" data-commentRating="0" 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:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571037"> <div class="moveup"> <div class="ttypography"><p>I did the same, but this is not O(N). The time Complexity will be O(n + maxELE) where maxELE is the largest sequence element seen in input.</p><p>We were lucky that the constraint on that wasn't 10^9.</p><p>Also consider cases in which n = 5 but the elements are still very large, our code would still take lot of time to execute.</p></div> </div> </div> <div class="reply info"> <a class="comment-571037 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571037 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571037"> <li> <div class="comment"> <table class="comment-table" commentId="571654" commentParentId="571037"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 18:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571654" href="?#comment-571654" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571037" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571654" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571654"> <div class="moveup"> <div class="ttypography"><p>Yeah that's true, the editorial's solution is more general for that same reason</p></div> </div> </div> <div class="reply info"> <a class="comment-571654 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571654 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571654"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571551" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571551" href="?#comment-571551" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571551" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571551"> <div class="moveup"> <div class="ttypography"><p>I cant understand the minfreq[i]=minfreq[i−1]+minfreq[i] . can you explain me </p></div> </div> </div> <div class="reply info"> <a class="comment-571551 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571551 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571551"> <li> <div class="comment"> <table class="comment-table" commentId="571653" commentParentId="571551"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571653" href="?#comment-571653" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571551" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571653" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571653"> <div class="moveup"> <div class="ttypography"><p>It's called accumulated sum. Basically we want minfreq[i] to be the frequency of all numbers $$$\leq$$$ to i, so we need to push our previous array position to our current one, so that we also take into account the occurences of numbers &lt; i, and not just equal to i</p></div> </div> </div> <div class="reply info"> <a class="comment-571653 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571653 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571653"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571001" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Aguin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Aguin" title="Candidate Master Aguin" class="rated-user user-violet">Aguin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571001" href="?#comment-571001" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571001" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="297931" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571001"> <div class="moveup"> <div class="ttypography"><p>How to count different quadrilaterals in problem E?</p></div> </div> </div> <div class="reply info"> <a class="comment-571001 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571001 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571001"> <li> <div class="comment"> <table class="comment-table" commentId="571004" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571004" href="?#comment-571004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571004"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571004"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571007" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 05:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571007" href="?#comment-571007" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571007" class="CommentVoteFrame" data-commentRating="3" 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;">+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-571007"> <div class="moveup"> <div class="ttypography"><p>For example, for each pair of points $$$(i, j)$$$, we can find the number of points on one side of the line i-j ($$$a$$$), the number of points on the other side ($$$N-2-a$$$), sum that up, divide by 2 and subtract $$$2{N\choose 4}$$$. Why? For each 4-tuple of points, if one of them is inside the triangle formed by the other 3 (their convex hull is a triangle), we get 3 lines (inner point, some other point) that are counted here, and when their convex hull is a quadrilateral, we get 2 such lines — its diagonals; we subtract (2 * number of 4-tuples) to get the number of 4-tuples where one point is inside.</p><p>How to find these $$$a$$$ for each pair $$$(i, j)$$$ fast? Let's say that $$$i$$$ is fixed, sort all remaining points by their angle around point $$$i$$$, then consider a line that crosses $$$i$$$, start rotating it and whenever it crosses one of these points, update the current value of $$$a$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-571007 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571007 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571007"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571011" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571011" href="?#comment-571011" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571011" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571011"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> (<a href="/topic/73334/en9">previous revision</a>, <a href="/topic/73334/en10">new revision</a>, <a href="/topic/73334/diff/en9/en10">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-571011 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571011 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571011"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hd7" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Hd7" title="Specialist Hd7" class="rated-user user-cyan">Hd7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571018" href="?#comment-571018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571018" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="559666" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571018"> <div class="moveup"> <div class="ttypography"><p>Could anyone give me a more elaborated explanation for problem D, I didn't grasp the editorial at all.</p></div> </div> </div> <div class="reply info"> <a class="comment-571018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571031" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571031" href="?#comment-571031" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571031" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571031"> <div class="moveup"> <div class="ttypography"><p>Expected a matroid problem, as <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> took matroid class last semester XD</p></div> </div> </div> <div class="reply info"> <a class="comment-571031 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571031 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571031"> <li> <div class="comment"> <table class="comment-table" commentId="571033" commentParentId="571031"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571033" href="?#comment-571033" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571031" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571033" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571033"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/team/65651">matroid fan club!</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571033 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571033 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571033"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571040" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PouyaNavid" style="position: relative;"> <img src='https://userpic.codeforces.org/670316/avatar/c42e949ea38011da.jpg'/> </a> <div><a href="/profile/PouyaNavid" title="Master PouyaNavid" class="rated-user user-orange">PouyaNavid</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 09:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571040" href="?#comment-571040" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571040" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="670316" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571040"> <div class="moveup"> <div class="ttypography"><p>Hack Test for D <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a></p><p>4 1 10 51 60 2 20 44 52 3 40 43 45 42 45 50 50</p></div> </div> </div> <div class="reply info"> <a class="comment-571040 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571040 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571040"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571088" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hazyknight" style="position: relative;"> <img src='https://userpic.codeforces.org/537474/avatar/e2c88ee4c2562699.jpg'/> </a> <div><a href="/profile/Hazyknight" title="International Grandmaster Hazyknight" class="rated-user user-red">Hazyknight</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571088" href="?#comment-571088" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571088" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571088" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="537474" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571088"> <div class="moveup"> <div class="ttypography"><p>Actually, Problem G can be solved easily by matroid intersection. Consider two matroid M1(S,I),M2(S,I), S is the set of wall, M1 is a graph matroid , M2 is a matroid which any black cell has at least to side without wall. Code: <a href="https://codeforces.com/contest/1284/submission/68215804">https://codeforces.com/contest/1284/submission/68215804</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571088 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571088 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571088"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571128" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amstan" style="position: relative;"> <img src='https://userpic.codeforces.org/734003/avatar/344c500da9a98a7f.jpg'/> </a> <div><a href="/profile/amstan" title="Expert amstan" class="rated-user user-blue">amstan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571128" href="?#comment-571128" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571128" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="734003" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571128"> <div class="moveup"> <div class="ttypography"><p>Is there anyone who solved D using coordinate compression and prefix sum ? If so, could you please share your submission.</p></div> </div> </div> <div class="reply info"> <a class="comment-571128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571128"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571138" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HaoxuanXIE" style="position: relative;"> <img src='https://userpic.codeforces.org/1234114/avatar/fa4b56dfead7992e.jpg'/> </a> <div><a href="/profile/HaoxuanXIE" title="Expert HaoxuanXIE" class="rated-user user-blue">HaoxuanXIE</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571138" href="?#comment-571138" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571138" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1234114" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571138"> <div class="moveup"> <div class="ttypography"><p>Why does D need to check in two directions? If I check in one direction, I get wrong answer at 9th point. But I think it is appropriate to check in only one direction.</p></div> </div> </div> <div class="reply info"> <a class="comment-571138 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571138 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571138"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571145" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheeLooser" style="position: relative;"> <img src='https://userpic.codeforces.org/448032/avatar/d5dcfa8c5dbd255f.jpg'/> </a> <div><a href="/profile/TheeLooser" title="Expert TheeLooser" class="rated-user user-blue">TheeLooser</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571145" href="?#comment-571145" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571145" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="448032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571145"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> may as well check how many visits were made to <a href="https://codeforces.com/problemset/problem/1146/H">this</a> page and later to <a href="https://codeforces.com/blog/entry/66639">this</a> page in contest time</p></div> </div> </div> <div class="reply info"> <a class="comment-571145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571145"> <li> <div class="comment"> <table class="comment-table" commentId="571459" commentParentId="571145"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 22:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571459" href="?#comment-571459" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571145" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571459" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571459"> <div class="moveup"> <div class="ttypography"><p>How does that problem help?</p></div> </div> </div> <div class="reply info"> <a class="comment-571459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571459"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571509" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Petr" style="position: relative;"> <img src='https://userpic.codeforces.org/664/avatar/a113c1791cdcd2e1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Petr" title="Legendary Grandmaster Petr" class="rated-user user-legendary"><span class="legendary-user-first-letter">P</span>etr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 01:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571509" href="?#comment-571509" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571509" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="664" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571509"> <div class="moveup"> <div class="ttypography"><p>Re: &quot;Hopefully, the first 80 tests were good enough for the contest.&quot;</p><p>My <a href="https://codeforces.com/contest/1284/submission/68208450">random solution</a> fails on test 87 :) Great job making the tests indeed!</p></div> </div> </div> <div class="reply info"> <a class="comment-571509 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571509 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571509"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571522" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MubtasimShahriar" style="position: relative;"> <img src='https://userpic.codeforces.org/756984/avatar/9113baa4abf04299.jpg'/> </a> <div><a href="/profile/MubtasimShahriar" title="Pupil MubtasimShahriar" class="rated-user user-green">MubtasimShahriar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 05:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571522" href="?#comment-571522" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571522" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756984" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571522"> <div class="moveup"> <div class="ttypography"><p>In Problem D, why does this solution not work? My Solutions is this.</p><p>Sort lectures according to their start-ending time in both venue, Then decide every lecture if it intersects with others in their own venue.</p><p>If there is at least one lecture that make difference in intersecting in both venue, then Subset can not be made. So the answer is no. If every problem either intersects in both venue or does not intersect in both venue then answer is yes. Here is my implementation <a href="/contest/1284/submission/68294866" title="Submission 68294866 by MubtasimShahriar">68294866</a></p><p>Please someone enlighten me where I am misunderstanding.</p></div> </div> </div> <div class="reply info"> <a class="comment-571522 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571522 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571522"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571546" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SLIMSHADYNICK" style="position: relative;"> <img src='https://userpic.codeforces.org/598862/avatar/7629f1b29f0fe807.jpg'/> </a> <div><a href="/profile/SLIMSHADYNICK" title="Candidate Master SLIMSHADYNICK" class="rated-user user-violet">SLIMSHADYNICK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571546" href="?#comment-571546" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571546" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-13" data-commentUserId="598862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-571546"> <div class="moveup"> <div class="ttypography"><p>In problem D, I got wrong answer on test case 14. Can somebody please help.</p></div> </div> </div> <div class="reply info"> <a class="comment-571546 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571546 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571546"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572491" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ftiasch" style="position: relative;"> <img src='https://userpic.codeforces.org/506/avatar/c52be21fbeb4a450.jpg'/> </a> <div><a href="/profile/ftiasch" title="International Grandmaster ftiasch" class="rated-user user-red">ftiasch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/11/2020 00:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572491" href="?#comment-572491" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572491" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="506" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-572491"> <div class="moveup"> <div class="ttypography"><p>2020 begins with two matroid problems. XD</p><p>btw, Challenge in Problem F is called Strong Basis Exchange as in <a href="https://math.mit.edu/~goemans/18438F09/lec11.pdf">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-572491 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572491 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572491"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572780" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Akash79" style="position: relative;"> <img src='https://userpic.codeforces.org/776725/avatar/700a28ac96121584.jpg'/> </a> <div><a href="/profile/Akash79" title="Expert Akash79" class="rated-user user-blue">Akash79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 16:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572780" href="?#comment-572780" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572780" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="776725" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572780"> <div class="moveup"> <div class="ttypography"><p>I am not able to understand problem B's solution.. can anyone please help me out..??</p></div> </div> </div> <div class="reply info"> <a class="comment-572780 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572780 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572780"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 17:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572849" href="?#comment-572849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="572849" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="572849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572849"> <div class="moveup"> <div class="ttypography"><p>Why don't we have to consider the case when there's some period intersecting in A and not intersecting in B? Doesn't that mean that sometimes our code will say 'YES' but the answer is 'NO'. Why? <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a>. EDIT: Ok, I just didn't notice the part of the code where he does the same thing but reversed.</p></div> </div> </div> <div class="reply info"> <a class="comment-572849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572849"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572863" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 18:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572863" href="?#comment-572863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572863" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572863"> <div class="moveup"> <div class="ttypography"><p>What is the hash approach for the problem D?</p></div> </div> </div> <div class="reply info"> <a class="comment-572863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572863"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="576477" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anaksoleh" style="position: relative;"> <img src='https://userpic.codeforces.org/1170460/avatar/27d790d7abbbd3d9.jpg'/> </a> <div><a href="/profile/anaksoleh" title="Newbie anaksoleh" class="rated-user user-gray">anaksoleh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/30/2020 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576477" href="?#comment-576477" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576477" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170460" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-576477"> <div class="moveup"> <div class="ttypography"><p>there is a proof for C solution ?</p></div> </div> </div> <div class="reply info"> <a class="comment-576477 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576477 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576477"> <li> <div class="comment"> <table class="comment-table" commentId="673042" commentParentId="576477"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/XORring-Samurai" style="position: relative;"> <img src='https://userpic.codeforces.org/1384228/avatar/d0258d5ed6604923.jpg'/> </a> <div><a href="/profile/XORring-Samurai" title="Candidate Master XORring-Samurai" class="rated-user user-violet">XORring-Samurai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/02/2020 09:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-673042" href="?#comment-673042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-576477" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="673042" 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="673042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1384228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-673042"> <div class="moveup"> <div class="ttypography"><p>Here is something, that I could think of.</p><p>For each permutation, we have the same $$$r-l$$$. This value varies from $$$0$$$ to $$$n-1$$$ for all $$$n$$$. Now let us consider $$$r-l=d$$$, as a general case. </p><p>For each $$$n$$$, we have $$$n-d$$$ pairs of $$$[l, r]$$$, where $$$r-l=d$$$. Also for all numbers from $$$1$$$ to $$$n$$$, we have $$$n-d$$$ pairs of type $$$[i, j]$$$ such that $$$j-i=d$$$. </p><p>For a segment to be framed, all the other places for each $$$[l, r]$$$ must be occupied by each integer from $$$[i, j]$$$. Therefore, we have $$$d+1$$$ numbers to be arranged in this interval $$$[l, r]$$$ and $$$n-d-1$$$ to be arranged in $$$[1, l-1]$$$ and $$$[r+1, n]$$$. This can be done in $$$(d+1)! * (n-d-1)!$$$ ways. </p><p>But we have $$$n-d$$$ pairs of $$$[l, r]$$$ and $$$n-d$$$ pairs of $$$[i, j]$$$, each of which can occupy this segment. Therefore the answer becomes summation over all $$$d$$$ from $$$0$$$ to $$$n-1$$$: $$$ans = ans + (n-d) * (n-d) * (d+1)! * (n-d-1)!$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-673042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-673042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-673042"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606852" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ThakurSaab" style="position: relative;"> <img src='https://userpic.codeforces.org/1267713/avatar/7c6c4d7b58cddb96.jpg'/> </a> <div><a href="/profile/ThakurSaab" title="Expert ThakurSaab" class="rated-user user-blue">ThakurSaab</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 17:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606852" href="?#comment-606852" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606852" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1267713" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606852"> <div class="moveup"> <div class="ttypography"><p>In problem C , do we consider that the numbers inside a particular segment [l,r] could be different such that, max-min = r-l</p></div> </div> </div> <div class="reply info"> <a class="comment-606852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606852"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="689589" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 07:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689589" href="?#comment-689589" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689589" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689589"> <div class="moveup"> <div class="ttypography"><p>In Problem D I added elements in the segment tree in the decreasing order of eai and then I queried for the previous range if the min of the ls and the maxr intersect with the particular index of a I am addding . I am getting a WA at Test Case 7 for this submission.</p><p>This is my submission link: <a href="https://codeforces.com/contest/1284/submission/91535000">https://codeforces.com/contest/1284/submission/91535000</a></p><p>Can somebody help me with this solution where I went wrong? </p><p>Or is there anyway I can look at the whole testcase then please reply here about how can I do that?</p></div> </div> </div> <div class="reply info"> <a class="comment-689589 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689589 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689589"> <li> <div class="comment"> <table class="comment-table" commentId="689595" commentParentId="689589"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 08:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689595" href="?#comment-689595" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-689589" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689595" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689595"> <div class="moveup"> <div class="ttypography"><p>Never Mind I made a silly typo in the cmp2 function.</p></div> </div> </div> <div class="reply info"> <a class="comment-689595 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689595 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689595"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="722358" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tanishq_code_c" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tanishq_code_c" title="Expert tanishq_code_c" class="rated-user user-blue">tanishq_code_c</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/17/2020 17:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-722358" href="?#comment-722358" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="722358" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1484322" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-722358"> <div class="moveup"> <div class="ttypography"><p>Hi, I am not able to understand the editorial for problem C. can anyone break it down in easy way please ? </p></div> </div> </div> <div class="reply info"> <a class="comment-722358 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-722358 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-722358"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="736312" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheOneYouWant" style="position: relative;"> <img src='https://userpic.codeforces.org/628619/avatar/c785428bde285c3.jpg'/> </a> <div><a href="/profile/TheOneYouWant" title="Master TheOneYouWant" class="rated-user user-orange">TheOneYouWant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/23/2020 05:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-736312" href="?#comment-736312" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="736312" class="CommentVoteFrame" data-commentRating="91" data-commentUserId="628619" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+91</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-736312"> <div class="moveup"> <div class="ttypography"><p>Hello, this seems to be broken (perhaps a sign of how the year 2020 has been so far)</p></div> </div> </div> <div class="reply info"> <a class="comment-736312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-736312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-736312"> <li> <div class="comment"> <table class="comment-table" commentId="737407" commentParentId="736312"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/27/2020 09:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-737407" href="?#comment-737407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-736312" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="737407" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-737407"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> please take a look, thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-737407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-737407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-737407"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741444" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/butterflies" style="position: relative;"> <img src='https://userpic.codeforces.org/1651561/avatar/33dfc9c16e5795ad.jpg'/> </a> <div><a href="/profile/butterflies" title="Specialist butterflies" class="rated-user user-cyan">butterflies</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741444" href="?#comment-741444" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="741444" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="741444" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1651561" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741444"> <div class="moveup"> <div class="ttypography"><p>This question relates to <a href="https://codeforces.com/contest/1284/problem/B">problem B</a>. I have a question with the second example input. Here is the input:</p> <pre><code>3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 </code></pre><p>I believe all arrays have an ascent. In the first array, the pair $$$(i, j) = (3, 4)$$$ works. ($$$a_3 = 0, a_4 = 2.$$$) In the second array, the pair $$$(i, j) = (1, 2)$$$ works. ($$$a_1 = 6, a_2 = 9.$$$) In the third array, the pair $$$(i,j) = (1, 2)$$$ works. ($$$a_1 = 1, a_2 = 6.$$$)</p><p>Thus, shouldn't all pairs of arrays in this case work? There are $$$9$$$ such pairs, but the answer to this should be $$$7.$$$ What is wrong with my reasoning here?</p></div> </div> </div> <div class="reply info"> <a class="comment-741444 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741444 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741444"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741445" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/beetroot" style="position: relative;"> <img src='https://userpic.codeforces.org/1503072/avatar/6668dbf5be4e4495.jpg'/> </a> <div><a href="/profile/beetroot" title="Expert beetroot" class="rated-user user-blue">beetroot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741445" href="?#comment-741445" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741445" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1503072" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741445"> <div class="moveup"> <div class="ttypography"><p>Editorials that didn't age well...</p></div> </div> </div> <div class="reply info"> <a class="comment-741445 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741445 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741445"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741475" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 07:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741475" href="?#comment-741475" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741475" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741475"> <div class="moveup"> <div class="ttypography"><p>Sorry for the issue with editorials. I think there is a timeout issue from Polygon. Since I can't resolve it, I will just rewrite it as a PDF form and upload here.</p></div> </div> </div> <div class="reply info"> <a class="comment-741475 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741475 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741475"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="797067" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/YPK" style="position: relative;"> <img src='https://userpic.codeforces.org/1489397/avatar/bd42de2aca7084dd.jpg'/> </a> <div><a href="/profile/YPK" title="Master YPK" class="rated-user user-orange">YPK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/29/2021 11:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-797067" href="?#comment-797067" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="797067" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="797067" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1489397" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-797067"> <div class="moveup"> <div class="ttypography"><p>Weak test cases for D. Consider the following test case </p> <pre><code>3 1 3 1 2 4 6 4 5 5 7 2 3 </code></pre><p>My accepted solution gives YES but the answer is NO.</p></div> </div> </div> <div class="reply info"> <a class="comment-797067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-797067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-797067"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="891199" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav04" style="position: relative;"> <img src='https://userpic.codeforces.org/2093148/avatar/b05253879beed26d.jpg'/> </a> <div><a href="/profile/abhinav04" title="Specialist abhinav04" class="rated-user user-cyan">abhinav04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/27/2022 11:56">19 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-891199" href="?#comment-891199" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="891199" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="2093148" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-891199"> <div class="moveup"> <div class="ttypography"><p>In case someone needs help with problem B, this might help.</p> <div class="spoiler"><b class="spoiler-title">submission</b><div class="spoiler-content" style="display: none;"><p><a href="https://codeforces.com/contest/1284/submission/147841447">https://codeforces.com/contest/1284/submission/147841447</a></p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-891199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-891199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-891199"> </ul> </div> <br/> <div id="editBox-78289" 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 firstPreview78289 = true; var lastPreviewContent78289 = ''; 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=78289] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=78289] 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-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, 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:27:29</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81288aad58e60057',t:'MTY5NjcwNjg0OS42NzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1284C
1284
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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Напомним, что перестановкой является массив, состоящий из $$$n$$$ различных целых чисел от $$$1$$$ до $$$n$$$ в произвольном порядке. Например, $$$[2,3,1,5,4]$$$ — перестановка, но $$$[1,2,2]$$$ не перестановка ($$$2$$$ встречается в массиве дважды) и $$$[1,3,4]$$$ тоже не перестановка ($$$n=3$$$, но в массиве встречается $$$4$$$).</p><p>Последовательность $$$a$$$ является подотрезком $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца. Обозначим подотрезок как $$$[l, r]$$$, где $$$l, r$$$ — целые числа и $$$1 \le l \le r \le n$$$. Это обозначает подотрезок, у которого убрали $$$l-1$$$ элементов слева и $$$n-r$$$ справа.</p><p>Для перестановки $$$p_1, p_2, \ldots, p_n$$$ назовём <span class="tex-font-style-it">рамочным подотрезком</span> такой подотрезок индексов $$$[l,r]$$$, в котором $$$\max\{p_l, p_{l+1}, \dots, p_r\} - \min\{p_l, p_{l+1}, \dots, p_r\} = r - l$$$. Например, у перестановки $$$(6, 7, 1, 8, 5, 3, 2, 4)$$$ некоторые из рамочных подотрезков: $$$[1, 2], [5, 8], [6, 7], [3, 3], [8, 8]$$$. В частности, подотрезок $$$[i,i]$$$ всегда является рамочным подотрезком для любого $$$i$$$ от $$$1$$$ до $$$n$$$ включительно.</p><p>Для перестановки $$$p$$$ определим <span class="tex-font-style-it">счастье перестановки</span> как количество таких пар $$$(l, r)$$$, что $$$1 \le l \le r \le n$$$ и $$$[l, r]$$$ является рамочным подотрезком. Например, перестановка $$$[3, 1, 2]$$$ имеет счастье $$$5$$$: Все подотрезки индексов кроме $$$[1, 2]$$$ являются рамочными.</p><p>Даны два целых числа $$$n$$$ и $$$m$$$. Джонгвон хочет найти суммарное счастье всех перестановок длины $$$n$$$ по модулю простого числа $$$m$$$. Обратите внимание, что всего существует $$$n!$$$ (факториал $$$n$$$) различных перестановок длины $$$n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 250\,000$$$, $$$10^8 \le m \le 10^9$$$, $$$m$$$ — простое).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$r$$$ ($$$0 \le r &lt; m$$$) — суммарное счастье всех перестановок длины $$$n$$$ по модулю простого числа $$$m$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 993244853 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 993244853 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 993244853 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 32 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2019 993244853 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 923958830 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2020 437122297 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 265955509 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Пусть $$$n=3$$$, тогда рассмотрим все перестановки длиной $$$3$$$:</p><ul> <li> $$$[1, 2, 3]$$$, все подотрезки являются рамочными подотрезками. Счастье равно $$$6$$$. </li><li> $$$[1, 3, 2]$$$, все подотрезки, кроме $$$[1, 2]$$$, являются рамочными подотрезками. Счастье равно $$$5$$$. </li><li> $$$[2, 1, 3]$$$, все подотрезки, кроме $$$[2, 3]$$$, являются рамочными подотрезками. Счастье равно $$$5$$$. </li><li> $$$[2, 3, 1]$$$, все подотрезки, кроме $$$[2, 3]$$$, являются рамочными подотрезками. Счастье равно $$$5$$$. </li><li> $$$[3, 1, 2]$$$, все подотрезки, кроме $$$[1, 2]$$$, являются рамочными подотрезками. Счастье равно $$$5$$$. </li><li> $$$[3, 2, 1]$$$, все подотрезки являются рамочными подотрезками. Счастье равно $$$6$$$. </li></ul><p>Поэтому суммарное счастье равно $$$6+5+5+5+5+6 = 32$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="9caf5c3a8dbc084c93d6c29847d525d1"/> <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="844107ee75ef6ee8a5d433a0bcfbbda150cb7f74"/> <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='9caf5c3a8dbc084c93d6c29847d525d1'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1284%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='9caf5c3a8dbc084c93d6c29847d525d1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1284">Hello 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='9caf5c3a8dbc084c93d6c29847d525d1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1284/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='9caf5c3a8dbc084c93d6c29847d525d1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="508364"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9caf5c3a8dbc084c93d6c29847d525d1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="508364"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72725" title="Hello 2020" target="_blank">Hello 2020 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10228" resourceName="Hello 2020" resourceManual="true" src="//codeforces.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/72804" title="Hello 2020 Editorial" target="_blank">Hello 2020 Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10239" resourceName="Hello 2020 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/1284">Задачи</a></li> <li><a href="/contest/1284/submit">Отослать</a></li> <li><a href="/contest/1284/my">Мои посылки</a></li> <li><a href="/contest/1284/status">Статус</a></li> <li><a href="/contest/1284/hacks">Взломы</a></li> <li><a href="/contest/1284/room/1">Комната</a></li> <li><a href="/contest/1284/standings">Положение</a></li> <li><a href="/contest/1284/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a0006000e4d9f8237c016adb9bda278d88a49019"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Напомним, что перестановкой является массив, состоящий из $$$n$$$ различных целых чисел от $$$1$$$ до $$$n$$$ в произвольном порядке. Например, $$$[2,3,1,5,4]$$$ — перестановка, но $$$[1,2,2]$$$ не перестановка ($$$2$$$ встречается в массиве дважды) и $$$[1,3,4]$$$ тоже не перестановка ($$$n=3$$$, но в массиве встречается $$$4$$$).</p><p>Последовательность $$$a$$$ является подотрезком $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца. Обозначим подотрезок как $$$[l, r]$$$, где $$$l, r$$$ — целые числа и $$$1 \le l \le r \le n$$$. Это обозначает подотрезок, у которого убрали $$$l-1$$$ элементов слева и $$$n-r$$$ справа.</p><p>Для перестановки $$$p_1, p_2, \ldots, p_n$$$ назовём <span class="tex-font-style-it">рамочным подотрезком</span> такой подотрезок индексов $$$[l,r]$$$, в котором $$$\max\{p_l, p_{l+1}, \dots, p_r\} - \min\{p_l, p_{l+1}, \dots, p_r\} = r - l$$$. Например, у перестановки $$$(6, 7, 1, 8, 5, 3, 2, 4)$$$ некоторые из рамочных подотрезков: $$$[1, 2], [5, 8], [6, 7], [3, 3], [8, 8]$$$. В частности, подотрезок $$$[i,i]$$$ всегда является рамочным подотрезком для любого $$$i$$$ от $$$1$$$ до $$$n$$$ включительно.</p><p>Для перестановки $$$p$$$ определим <span class="tex-font-style-it">счастье перестановки</span> как количество таких пар $$$(l, r)$$$, что $$$1 \le l \le r \le n$$$ и $$$[l, r]$$$ является рамочным подотрезком. Например, перестановка $$$[3, 1, 2]$$$ имеет счастье $$$5$$$: Все подотрезки индексов кроме $$$[1, 2]$$$ являются рамочными.</p><p>Даны два целых числа $$$n$$$ и $$$m$$$. Джонгвон хочет найти суммарное счастье всех перестановок длины $$$n$$$ по модулю простого числа $$$m$$$. Обратите внимание, что всего существует $$$n!$$$ (факториал $$$n$$$) различных перестановок длины $$$n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 250\,000$$$, $$$10^8 \le m \le 10^9$$$, $$$m$$$ — простое).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$r$$$ ($$$0 \le r &lt; m$$$) — суммарное счастье всех перестановок длины $$$n$$$ по модулю простого числа $$$m$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 993244853 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 993244853 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 993244853 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 32 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2019 993244853 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 923958830 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2020 437122297 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 265955509 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Пусть $$$n=3$$$, тогда рассмотрим все перестановки длиной $$$3$$$:</p><ul> <li> $$$[1, 2, 3]$$$, все подотрезки являются рамочными подотрезками. Счастье равно $$$6$$$. </li><li> $$$[1, 3, 2]$$$, все подотрезки, кроме $$$[1, 2]$$$, являются рамочными подотрезками. Счастье равно $$$5$$$. </li><li> $$$[2, 1, 3]$$$, все подотрезки, кроме $$$[2, 3]$$$, являются рамочными подотрезками. Счастье равно $$$5$$$. </li><li> $$$[2, 3, 1]$$$, все подотрезки, кроме $$$[2, 3]$$$, являются рамочными подотрезками. Счастье равно $$$5$$$. </li><li> $$$[3, 1, 2]$$$, все подотрезки, кроме $$$[1, 2]$$$, являются рамочными подотрезками. Счастье равно $$$5$$$. </li><li> $$$[3, 2, 1]$$$, все подотрезки являются рамочными подотрезками. Счастье равно $$$6$$$. </li></ul><p>Поэтому суммарное счастье равно $$$6+5+5+5+5+6 = 32$$$.</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:54: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:'8124930f5a32167e',t:'MTY5NjY2NTI0OS4yNzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1600"]
https://codeforces.com/blog/entry/72804
<!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="17bb3c0a988bbcfabcfbab3b80b286ce"/> <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="Hello 2020 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>Hello 2020 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='17bb3c0a988bbcfabcfbab3b80b286ce'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F72804">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='17bb3c0a988bbcfabcfbab3b80b286ce'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:37:33</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:37:33</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div><div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='17bb3c0a988bbcfabcfbab3b80b286ce'/> <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/ko_osaga">ko_osaga</a></li> <li class="current selectedLava"><a href="/blog/ko_osaga">Blog</a></li> <li><a href="/teams/with/ko_osaga">Teams</a></li> <li><a href="/submissions/ko_osaga">Submissions</a></li> <li><a href="/groups/with/ko_osaga">Groups</a></li> <li><a href="/contests/with/ko_osaga">Contests</a></li> <li><a href="/contests/writer/ko_osaga">Problemsetting</a></li> <li><a href="/streams/ko_osaga">Streams</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ko_osaga" style="text-decoration:none;color:black !important;">ko_osaga's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="73334"> <div class="title"> <a href="/blog/entry/72804"> <p>Hello 2020 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a>, <a href="/topic/73334/en12">history</a>, <span class="format-humantime" title="Jan/04/2020 18:44">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>Since the Polygon tutorial system is currently broken, I will replace the editorial with PDF format. Sorry for the inconvenience!</p><p><a href="https://www.dropbox.com/s/ysttw748rvx46eb/Hello%202020.pdf?dl=0">Solution PDF</a></p><p>Problem A was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203276">Code</a></p><p>Problem B was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203332">Code</a></p><p>Problem C was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203721">Code</a></p><p>Problem D was authored by <a class="rated-user user-orange" href="/profile/nong" title="Master nong">nong</a>. <a href="https://codeforces.com/contest/1284/submission/68203704">Code</a></p><p>Problem E was authored by <a class="rated-user user-orange" href="/profile/ckw1140" title="Master ckw1140">ckw1140</a>. <a href="https://codeforces.com/contest/1284/submission/68203754">Code</a></p><p>Problem F was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203787">Code</a></p><p>Problem G was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203817">Code</a></p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1284" class="notice" style="text-decoration: none;">Hello 2020</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-38652-73334").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "38652", blogEntryId: "72804", 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-73334"><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'>+191</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-73334"><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/ko_osaga"><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/ko_osaga"> ko_osaga </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="Jan/04/2020 18:44">4 years ago</span> </li> <li> <a href="/blog/entry/72804#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/72804#comments"> 157 </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="78289"> <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 (143)</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="570690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SHZhang" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SHZhang" title="International Grandmaster SHZhang" class="rated-user user-red">SHZhang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570690" href="?#comment-570690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570690" class="CommentVoteFrame" data-commentRating="50" data-commentUserId="1150683" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+50</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570690"> <div class="moveup"> <div class="ttypography"><p>When I open the editorial for problem E, I see the editorial for problem C instead. Can the author fix this, please?</p></div> </div> </div> <div class="reply info"> <a class="comment-570690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570690"> <li> <div class="comment"> <table class="comment-table" commentId="570700" commentParentId="570690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570700" href="?#comment-570700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570700" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570700"> <div class="moveup"> <div class="ttypography"><p>Sorry, it's fixed now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570700"> <li> <div class="comment"> <table class="comment-table" commentId="598782" commentParentId="570700"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jokerwyt" style="position: relative;"> <img src='https://userpic.codeforces.org/555567/avatar/247d0346874bdbdd.jpg'/> </a> <div><a href="/profile/jokerwyt" title="Candidate Master jokerwyt" class="rated-user user-violet">jokerwyt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/07/2020 16:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-598782" href="?#comment-598782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570700" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="598782" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555567" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-598782"> <div class="moveup"> <div class="ttypography"><p>Challenge of problem E is nice, but i have no idea how to solve it. Could you provide the solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-598782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-598782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-598782"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/21August" style="position: relative;"> <img src='https://userpic.codeforces.org/452773/avatar/13e016fa74fb3308.jpg'/> </a> <div><a href="/profile/21August" title="Master 21August" class="rated-user user-orange">21August</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570691" href="?#comment-570691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570691" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="452773" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570691"> <div class="moveup"> <div class="ttypography"><p>You got it wrong for E.</p></div> </div> </div> <div class="reply info"> <a class="comment-570691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570691"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570695" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 18:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570695" href="?#comment-570695" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570695" 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-570695"> <div class="moveup"> <div class="ttypography"><p>Really liked problems B and C :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570695"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570706" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TimonKnigge" style="position: relative;"> <img src='https://userpic.codeforces.org/275246/avatar/debe81b88ed671c2.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/TimonKnigge" title="Master TimonKnigge" class="rated-user user-orange">TimonKnigge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570706" href="?#comment-570706" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570706" class="CommentVoteFrame" data-commentRating="86" data-commentUserId="275246" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+86</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570706"> <div class="moveup"> <div class="ttypography"><p>Problem D is a lot more intuitive if you interpret the input as a collection of rectangles, where you are asked if there is a pair of rectangles that overlaps on one axis but not the other. Then a scanline solution is obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-570706 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570706 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570706"> <li> <div class="comment"> <table class="comment-table" commentId="570804" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Skeef79" style="position: relative;"> <img src='https://userpic.codeforces.org/631759/avatar/3033511aaec49179.jpg'/> </a> <div><a href="/profile/Skeef79" title="Candidate Master Skeef79" class="rated-user user-violet">Skeef79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570804" href="?#comment-570804" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570804"> <div class="moveup"> <div class="ttypography"><p>Can you please give some good resources about scanline? </p></div> </div> </div> <div class="reply info"> <a class="comment-570804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570804"> <li> <div class="comment"> <table class="comment-table" commentId="570996" commentParentId="570804"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rezwan.Arefin01" style="position: relative;"> <img src='https://userpic.codeforces.org/358701/avatar/68ec3668b1ccc552.jpg'/> </a> <div><a href="/profile/Rezwan.Arefin01" title="Candidate Master Rezwan.Arefin01" class="rated-user user-violet">Rezwan.Arefin01</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570996" href="?#comment-570996" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570804" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570996" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="358701" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570996"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.topcoder.com/community/competitive-programming/tutorials/line-sweep-algorithms/">Topcoder Tutorials</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570996 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570996 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570996"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570807" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570807" href="?#comment-570807" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570807" class="CommentVoteFrame" data-commentRating="33" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+33</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570807"> <div class="moveup"> <div class="ttypography"><p>That was the original formulation. I came up with the conference statement to make this problem much natural ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-570807 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570807 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570807"> <li> <div class="comment"> <table class="comment-table" commentId="571201" commentParentId="570807"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ghoshsai5000" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ghoshsai5000" title="Pupil ghoshsai5000" class="rated-user user-green">ghoshsai5000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571201" href="?#comment-571201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570807" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571201" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="543439" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571201"> <div class="moveup"> <div class="ttypography"><p>This was eye-opening ! So, the input format is $$$x_1, x_2, y_1, y_2$$$ and we have to look for $$$2$$$ rectangles such that their $$$x$$$-axes coincide but their $$$y$$$ do not or the other way around. </p><p>First time, we sort by $$$x$$$ and for every new line segment we process, we keep track of all the line segments it inserts with. We will check if the corresponding $$$y$$$ of the line segment fits in the bounds of all the line segments it has intersected so far. </p> <ul> <li>$$$y_1$$$ should not be greater than the smallest $$$y_2$$$ seen so far.</li> <li>$$$y_2$$$ should not be lesser than the greatest $$$y_1$$$ seen so far.</li> </ul><p>If you could include this interpretation in the editorial, it would help in understanding a lot :)</p></div> </div> </div> <div class="reply info"> <a class="comment-571201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571201"> <li> <div class="comment"> <table class="comment-table" commentId="571683" commentParentId="571201"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 19:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571683" href="?#comment-571683" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571683" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571683" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571683"> <div class="moveup"> <div class="ttypography"><p>To be honest, I think it very much depends on what you're comfortable with (Specifically, users who love geometry would love this interpretation). For me, it was easier to visualize the problem in the current format (interval format), whereas it took me a while to grasp the rectangle interpretation. It is interesting to see how the problem can be solved in so similar ways for seemingly different interpretations.</p></div> </div> </div> <div class="reply info"> <a class="comment-571683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571683"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="574189" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sthfaceless" style="position: relative;"> <img src='https://userpic.codeforces.org/1176362/avatar/4480df56f05c4612.jpg'/> </a> <div><a href="/profile/sthfaceless" title="Candidate Master sthfaceless" class="rated-user user-violet">sthfaceless</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/18/2020 20:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-574189" href="?#comment-574189" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="574189" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1176362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-574189"> <div class="moveup"> <div class="ttypography"><p>I used it too :)</p></div> </div> </div> <div class="reply info"> <a class="comment-574189 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-574189 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-574189"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570710" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Radewoosh" style="position: relative;"> <img src='https://userpic.codeforces.org/147752/avatar/a91526f3bd0194e8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570710" href="?#comment-570710" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570710" class="CommentVoteFrame" data-commentRating="76" data-commentUserId="147752" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+76</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570710"> <div class="moveup"> <div class="ttypography"><p>When will we be able to submit?</p></div> </div> </div> <div class="reply info"> <a class="comment-570710 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570710 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570710"> <li> <div class="comment"> <table class="comment-table" commentId="570734" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570734" href="?#comment-570734" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570734" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-38" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570734"> <div class="moveup"> <div class="ttypography"><p>In most contests, submission window opens 2 hours after the contest I guess.</p></div> </div> </div> <div class="reply info"> <a class="comment-570734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570734"> <li> <div class="comment"> <table class="comment-table" commentId="570808" commentParentId="570734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WaterColor2037" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/WaterColor2037" title="Master WaterColor2037" class="rated-user user-orange">WaterColor2037</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570808" href="?#comment-570808" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570808" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="876428" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570808"> <div class="moveup"> <div class="ttypography"><p>Why people downvote this?</p></div> </div> </div> <div class="reply info"> <a class="comment-570808 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570808 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570808"> <li> <div class="comment"> <table class="comment-table" commentId="570811" commentParentId="570808"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:40">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570811" href="?#comment-570811" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570808" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570811" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570811"> <div class="moveup"> <div class="ttypography"><p>Because it isn't true. Usually you can submit a few minutes after system tests are over.</p></div> </div> </div> <div class="reply info"> <a class="comment-570811 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570811 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570811"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570748" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570748" href="?#comment-570748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570748" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570748"> <div class="moveup"> <div class="ttypography"><p>Now submission is open.</p></div> </div> </div> <div class="reply info"> <a class="comment-570748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570748"> <li> <div class="comment"> <table class="comment-table" commentId="570761" commentParentId="570748"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570761" href="?#comment-570761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570748" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570761" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570761"> <div class="moveup"> <div class="ttypography"><p>Exactly 2 hours :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570711" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570711" href="?#comment-570711" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570711" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570711"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/72725?#comment-570663">Randomised sol for D</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570711 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570711 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570711"> <li> <div class="comment"> <table class="comment-table" commentId="570714" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570714" href="?#comment-570714" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570714" class="CommentVoteFrame" data-commentRating="59" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+59</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570714"> <div class="moveup"> <div class="ttypography"><p>There is another randomized approach involving hashes. You may assign random number to each lecture and then calculate for each interval the xor of numbers assigned to intervals it intersects. Now you should check that every lecture has same hashes in first and second places...</p></div> </div> </div> <div class="reply info"> <a class="comment-570714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570714"> <li> <div class="comment"> <table class="comment-table" commentId="570730" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570730" href="?#comment-570730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570730"> <div class="moveup"> <div class="ttypography"><p>how do you calculate the xor of the intersections?</p></div> </div> </div> <div class="reply info"> <a class="comment-570730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570730"> <li> <div class="comment"> <table class="comment-table" commentId="570735" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570735" href="?#comment-570735" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570735" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570735" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570735"> <div class="moveup"> <div class="ttypography"><p>I think, scan-line should work. When the interval $$$[l_i,r_i]$$$ opens, you put $$$h_i$$$ in the position $$$r_i$$$ and when this interval closes you take the xor of all numbers on the $$$[l_i, \infty)$$$.</p><p>It should look like <a href="https://ideone.com/Dypu4W">this</a>, but it gets WA-6 and I'm to sleepy to debug it properly.</p></div> </div> </div> <div class="reply info"> <a class="comment-570735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570735"> <li> <div class="comment"> <table class="comment-table" commentId="570764" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570764" href="?#comment-570764" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570764" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570764"> <div class="moveup"> <div class="ttypography"><p>yeah I did same thing but i get wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570764"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571027" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bhj2001" style="position: relative;"> <img src='https://userpic.codeforces.org/602476/avatar/71790bb4a53d93d3.jpg'/> </a> <div><a href="/profile/Bhj2001" title="Master Bhj2001" class="rated-user user-orange">Bhj2001</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571027" href="?#comment-571027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="602476" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571027"> <div class="moveup"> <div class="ttypography"><p>the WA is not because of hash collision <br /> you missed the case when 2 intervals completely overlap</p></div> </div> </div> <div class="reply info"> <a class="comment-571027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571027"> <li> <div class="comment"> <table class="comment-table" commentId="571059" commentParentId="571027"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571059" href="?#comment-571059" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571027" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571059" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571059"> <div class="moveup"> <div class="ttypography"><p>Not really, I just made a silly typo in my segment tree code... I got it accepted now: <a href="/contest/1284/submission/68205086" title="Submission 68205086 by adamant">68205086</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571059 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571059 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571059"> <li> <div class="comment"> <table class="comment-table" commentId="576198" commentParentId="571059"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anodaram" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anodaram" title="International Master anodaram" class="rated-user user-orange">anodaram</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/29/2020 08:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576198" href="?#comment-576198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571059" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576198" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="1314285" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-576198"> <div class="moveup"> <div class="ttypography"><p>Segment Tree is more popular way than multiset for this problem, I think.</p></div> </div> </div> <div class="reply info"> <a class="comment-576198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576198"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570740" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amnesiac_dusk" style="position: relative;"> <img src='https://userpic.codeforces.org/630995/avatar/5c9b8d77d7e96eff.jpg'/> </a> <div><a href="/profile/amnesiac_dusk" title="Grandmaster amnesiac_dusk" class="rated-user user-red">amnesiac_dusk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570740" href="?#comment-570740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570740" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="630995" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570740"> <div class="moveup"> <div class="ttypography"><p>It can also be treated as hashing all maximal cliques of the interval graph which should be sufficient for checking the equality of the graphs as the graph is chordal. My code for reference <a href="/contest/1284/submission/68181402" title="Submission 68181402 by amnesiac_dusk">68181402</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570740"> <li> <div class="comment"> <table class="comment-table" commentId="571137" commentParentId="570740"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tejas_919" style="position: relative;"> <img src='https://userpic.codeforces.org/875719/avatar/25f822a14baf7fbf.jpg'/> </a> <div><a href="/profile/tejas_919" title="Master tejas_919" class="rated-user user-orange">tejas_919</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571137" href="?#comment-571137" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571137" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571137"> <div class="moveup"> <div class="ttypography"><p>Can you tell me where can I learn this stuff about graphs? It would be really helpful of you.</p></div> </div> </div> <div class="reply info"> <a class="comment-571137 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571137 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571137"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570799" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/staniewzki" style="position: relative;"> <img src='https://userpic.codeforces.org/838116/avatar/307490effa9e1ae7.jpg'/> </a> <div><a href="/profile/staniewzki" title="Grandmaster staniewzki" class="rated-user user-red">staniewzki</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570799" href="?#comment-570799" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570799" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838116" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570799"> <div class="moveup"> <div class="ttypography"><p>You can look at my submission, I kept two segment trees — in one i put the value of the lecture on the beggining of the lecture and in the other on the end. Then, for each lecture i checked for lectures than do not intersect, so lectures that have end before the current beggining and the same for other side. </p></div> </div> </div> <div class="reply info"> <a class="comment-570799 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570799 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570799"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571124" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nizil" style="position: relative;"> <img src='https://userpic.codeforces.org/250190/avatar/d1314e6f3fecc96f.jpg'/> </a> <div><a href="/profile/Nizil" title="Expert Nizil" class="rated-user user-blue">Nizil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571124" href="?#comment-571124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571124" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="250190" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571124"> <div class="moveup"> <div class="ttypography"><p>I have a rather neat code doing this that might help: <a href="/contest/1284/submission/68239280" title="Submission 68239280 by Nizil">68239280</a>. I used the formula:</p> <center>$$$\{\text{Lectures that intersect lecture $$$l$$$}\} = \{\text{Lectures that start before $$$l$$$ ends}\} \setminus \{\text{Lectures that end before $$$l$$$ starts}\}$$$</center><p>. Note that if a lecture ends before $$$l$$$ starts, then it also begins before $$$l$$$ ends so in the subtraction every element of the latter set is contained in the former set. Also note that we do a XOR both when we add and when we remove a set.</p></div> </div> </div> <div class="reply info"> <a class="comment-571124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571124"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570746" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570746" href="?#comment-570746" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570746" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570746" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570746"> <div class="moveup"> <div class="ttypography"><p>My solution uses hashes also :)</p><p>Let's calculate value $$$sumA=\sum_{i \, intersects \, j}(h_i\cdot h_j)$$$ by some modulo for segments in A and the same $$$sumB$$$ for segments in B. Here, $$$h_i$$$ are some random values. This can be calculated with scanline. The answer is &quot;YES&quot; iff $$$sumA=sumB$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570746 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570746 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570746"> <li> <div class="comment"> <table class="comment-table" commentId="570766" commentParentId="570746"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570766" href="?#comment-570766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570746" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570766"> <div class="moveup"> <div class="ttypography"><p>yeah me too but i got wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570766"> <li> <div class="comment"> <table class="comment-table" commentId="570861" commentParentId="570766"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570861" href="?#comment-570861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570766" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570861"> <div class="moveup"> <div class="ttypography"><p>Maybe my code will be helpful: <a href="/contest/1284/submission/68181544" title="Submission 68181544 by VladProg">68181544</a></p><p>It doesn't use any data structures. Only two scan lines.</p></div> </div> </div> <div class="reply info"> <a class="comment-570861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570861"> <li> <div class="comment"> <table class="comment-table" commentId="570871" commentParentId="570861"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570871" href="?#comment-570871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570871"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-570871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570871"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570903" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lemelisk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lemelisk" title="Master lemelisk" class="rated-user user-orange">lemelisk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570903" href="?#comment-570903" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570903" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="513315" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570903"> <div class="moveup"> <div class="ttypography"><p>You can just treat intersections as long number in binary notification (zero means no intersection with given index's segment, one means intersection) and use its remainder as hash. See my submission <a href="https://codeforces.com/contest/1284/submission/68191562">https://codeforces.com/contest/1284/submission/68191562</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570903 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570903 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570903"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571092" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571092" href="?#comment-571092" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571092" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571092"> <div class="moveup"> <div class="ttypography"><p>I just leave it here. I also assign random number to each lecture, and then calculate some hashes. But to avoid cases when one segment completely inside in other, I just took complement approach. I get hash of all segments that doesn't intersect with selected. They are those who ends before selected, or starts after selected. So, I have two BIT for each place: one for lectures ending at time X and one for lectures starting at time X. This is done with packed coordinates and four BIT for each set of random identifiers. <a href="/contest/1284/submission/68198554" title="Submission 68198554 by r57shell">68198554</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571092 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571092 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571092"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570994" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570994" href="?#comment-570994" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570994" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570994"> <div class="moveup"> <div class="ttypography"><p>Me too.</p></div> </div> </div> <div class="reply info"> <a class="comment-570994 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570994 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570994"> <li> <div class="comment"> <table class="comment-table" commentId="570995" commentParentId="570994"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570995" href="?#comment-570995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570994" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570995"> <div class="moveup"> <div class="ttypography"><p>My randomised solution also passed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570995"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570712" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/GyojunYoun" style="position: relative;"> <img src='https://userpic.codeforces.org/227186/avatar/84d3b7d6c6ddb05c.jpg'/> </a> <div><a href="/profile/GyojunYoun" title="Grandmaster GyojunYoun" class="rated-user user-red">GyojunYoun</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570712" href="?#comment-570712" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570712" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570712" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="227186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570712"> <div class="moveup"> <div class="ttypography"><p>Thank you for setting these wonderful problems. Unlike other geometry probs, E is so beautiful that I was impressed :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570712 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570712 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570712"> <li> <div class="comment"> <table class="comment-table" commentId="570805" commentParentId="570712"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mango_lassi" style="position: relative;"> <img src='https://userpic.codeforces.org/519408/avatar/69109d1881b4b829.jpg'/> </a> <div><a href="/profile/mango_lassi" title="International Grandmaster mango_lassi" class="rated-user user-red">mango_lassi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570805" href="?#comment-570805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570712" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-29" data-commentUserId="519408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570805"> <div class="moveup"> <div class="ttypography"><p>Just what part of E do you think is beautiful? I agree that the model solution doesn't seem bad, but that is only in comparison to how painful writing code for the not-totally-magic solutions is. A problem with many easy to find ugly solutions does not turn good from the existence of a beautiful solution that is very difficult to find.</p></div> </div> </div> <div class="reply info"> <a class="comment-570805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570805"> <li> <div class="comment"> <table class="comment-table" commentId="570812" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570812" href="?#comment-570812" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570812" class="CommentVoteFrame" data-commentRating="62" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+62</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570812"> <div class="moveup"> <div class="ttypography"><p>I don't get the point. If you failed to find good solution, then it's our fault?</p></div> </div> </div> <div class="reply info"> <a class="comment-570812 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570812 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570812"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570838" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570838" href="?#comment-570838" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570838" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570838" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570838"> <div class="moveup"> <div class="ttypography"><p>Well, I found it really interesting what you can solve it in $$$O(n^2)$$$. <a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a> is really similar problem and I believe it can only be solved in $$$O(n^3)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570838 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570838 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570838"> <li> <div class="comment"> <table class="comment-table" commentId="570840" commentParentId="570838"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570840" href="?#comment-570840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570838" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570840"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-red" href="/profile/OnionPringles" title="International Grandmaster OnionPringles">OnionPringles</a> told me about the $$$O(n^2\log n)$$$ solution of that problem. Of course, it's much harder than our problem's solution, in any aspect.</p></div> </div> </div> <div class="reply info"> <a class="comment-570840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570840"> <li> <div class="comment"> <table class="comment-table" commentId="570867" commentParentId="570840"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570867" href="?#comment-570867" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570867" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570867"> <div class="moveup"> <div class="ttypography"><p>After I found $$$3x_3+4x_4+5x_5$$$ I thought I need $$$x_5$$$... After 4 TLE attempts, I saw the magic :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570867 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570867 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570867"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570722" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iaNTU" style="position: relative;"> <img src='https://userpic.codeforces.org/568681/avatar/e2c4a458dc77ff9b.jpg'/> </a> <div><a href="/profile/iaNTU" title="International Master iaNTU" class="rated-user user-orange">iaNTU</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570722" href="?#comment-570722" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570722" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-15" data-commentUserId="568681" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570722"> <div class="moveup"> <div class="ttypography"><p>Seems like you don't understand what &quot;right after&quot; means.</p></div> </div> </div> <div class="reply info"> <a class="comment-570722 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570722 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570722"> <li> <div class="comment"> <table class="comment-table" commentId="570728" commentParentId="570722"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570728" href="?#comment-570728" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570722" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570728" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-16" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570728"> <div class="moveup"> <div class="ttypography"><p>Right after systest. I'm sorry for F.</p></div> </div> </div> <div class="reply info"> <a class="comment-570728 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570728 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570728"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570739" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570739" href="?#comment-570739" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570739" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570739"> <div class="moveup"> <div class="ttypography"><p>Does the following flow solution for F run in time?</p><p>Create three sets of nodes A, B, and C. A represents the first set of edges, C represents the second set of edges. We need to match as many nodes in A as we can with nodes in C. Set B represents all the nodes in the tree. Each node in A and C will be connected to the two nodes that the edge it represents in connected to. We then run flow from the nodes in A to the nodes in C.</p><p>This graph has O(n) edges and a max flow of O(n).</p></div> </div> </div> <div class="reply info"> <a class="comment-570739 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570739 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570739"> <li> <div class="comment"> <table class="comment-table" commentId="570749" commentParentId="570739"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570749" href="?#comment-570749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570739" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570749"> <div class="moveup"> <div class="ttypography"><p>Actually, nevermind, this just doesn't work</p></div> </div> </div> <div class="reply info"> <a class="comment-570749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570749"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570743" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/snorkel" style="position: relative;"> <img src='https://userpic.codeforces.org/1360865/avatar/4aa0ab75c5725b5.jpg'/> </a> <div><a href="/profile/snorkel" title="Expert snorkel" class="rated-user user-blue">snorkel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570743" href="?#comment-570743" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360865" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570743"> <div class="moveup"> <div class="ttypography"><p>When the codes will be available?</p></div> </div> </div> <div class="reply info"> <a class="comment-570743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570743"> <li> <div class="comment"> <table class="comment-table" commentId="570767" commentParentId="570743"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570767" href="?#comment-570767" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570743" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570767" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570767"> <div class="moveup"> <div class="ttypography"><p>Code is available now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570767"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570750" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570750" href="?#comment-570750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570750" class="CommentVoteFrame" data-commentRating="12" 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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570750"> <div class="moveup"> <div class="ttypography"><p>For F we can prove that answer always equals $$$n - 1$$$ easily using Hall theorem. Pick any $$$k$$$ edges in first tree, we want to prove that there are at least $$$k$$$ edges in the second tree which can be used to replace at least one of picked edges. Let's remove all picked edges from the tree, then it splits to $$$k + 1$$$ components. For each edge in the second tree let's draw an edge between components containing endpoints of the edge. Since the tree was connected before compressing edges it is still connected now, which means it has at least $$$k$$$ edges which are not self-loops, which means there are at least $$$k$$$ edges which can be used to replace one of picked edges.</p></div> </div> </div> <div class="reply info"> <a class="comment-570750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570750"> <li> <div class="comment"> <table class="comment-table" commentId="570752" commentParentId="570750"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 19:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570752" href="?#comment-570752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570750" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570752" 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-570752"> <div class="moveup"> <div class="ttypography"><p>Sadly this proof gives no clue on how to find the matching</p></div> </div> </div> <div class="reply info"> <a class="comment-570752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570752"> <li> <div class="comment"> <table class="comment-table" commentId="570774" commentParentId="570752"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570774" href="?#comment-570774" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570774" 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-570774"> <div class="moveup"> <div class="ttypography"><p>In my solution (tl;dr <a href="https://codeforces.com/blog/entry/72725?#comment-570604">here</a>), it just turns out while I'm looking for some characteristics of the matching that it is perfect, and the argument for that is kinda similar to Hall's theorem — it also deals with sets of edges in T2 and adjacent edges in T1. It doesn't seem to be particularly useful for finding a way to compute a matching quickly, though.</p></div> </div> </div> <div class="reply info"> <a class="comment-570774 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570774 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570774"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570772" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570772" href="?#comment-570772" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570772" class="CommentVoteFrame" data-commentRating="20" 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;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570772"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p><p>Pick a 1 edge (u, v) from the T1, s.t. u is the leaf in T1. We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A). We can find matching, (u, v) in T1 &amp; (u, w) in T2, and remove those edges. For all x($$$x \neq w$$$), if there is a edge (u, x) in T2, we change u to v. it means, remove (u, x) and add(v, x) (step B). As a result, we can remove vertexes u and reduce problem size by one(after operate, T2 remained as tree).</p><p>How to simulate? Bottleneck is the step B, changing (u, x) to (v, x). Therefore we don't change all edges, but simply remove (u, w) and add dummy edge (u, v). We have to find nearest non-dummy edge in step A, but it's all. We can easily do it by Link-Cut Tree</p></div> </div> </div> <div class="reply info"> <a class="comment-570772 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570772 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570772"> <li> <div class="comment"> <table class="comment-table" commentId="570782" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570782" href="?#comment-570782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570782" 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-570782"> <div class="moveup"> <div class="ttypography"><blockquote><p>We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A).</p> </blockquote><p>Tbh when you have this, there's no need for further tricks or LCT. Just HLD over T1, store not yet taken edges in each path in a set (ordered by depth), DFS over T2 and use HLD to simulate the process for each edge in T2. That's my solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-570782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570782"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570785" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OnionPringles" 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/OnionPringles" title="International Grandmaster OnionPringles" class="rated-user user-red">OnionPringles</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570785" href="?#comment-570785" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570785" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="360543" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570785"> <div class="moveup"> <div class="ttypography"><p>I solved step B by merging u,v in T2 by implementing union-find structure on LCT nodes. When merging u and v, cut all preferred children of u and v so that the children can go through union-find structure when they try to access the unpreferred parent. I think it is easy if you have a pre-written LCT code.</p></div> </div> </div> <div class="reply info"> <a class="comment-570785 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570785 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570785"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570791" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gamegame" style="position: relative;"> <img src='https://userpic.codeforces.org/352372/avatar/8717a5b44702348a.jpg'/> </a> <div><a href="/profile/gamegame" title="Legendary Grandmaster gamegame" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>amegame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570791" href="?#comment-570791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="352372" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570791"> <div class="moveup"> <div class="ttypography"><p>You can do binary lifting and dsu, which is much more easier to code than LCT/HLD</p></div> </div> </div> <div class="reply info"> <a class="comment-570791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570791"> <li> <div class="comment"> <table class="comment-table" commentId="571082" commentParentId="570791"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 12:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571082" href="?#comment-571082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570791" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571082" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571082"> <div class="moveup"> <div class="ttypography"><p>I had the same, but tbh in such contests it would be more preferable to just copy LCT.</p></div> </div> </div> <div class="reply info"> <a class="comment-571082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571082"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570884" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570884" href="?#comment-570884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570884" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570884"> <div class="moveup"> <div class="ttypography"><p>I updated my solution to F. It is my favorite in this problem set. Hope you liked it too!</p></div> </div> </div> <div class="reply info"> <a class="comment-570884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570884"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570783" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570783" href="?#comment-570783" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570783" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+61</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570783"> <div class="moveup"> <div class="ttypography"><p>Here is a more intuitive explanation for E. Sorry if it's mentioned already.</p><p>Fix the point $$$p$$$. Translate everything such that $$$p$$$ coincides with the origin. Sort all the other points counter-clockwise. We shall now find the number of quadruples of points that <em>don't</em> form a polygon containing $$$p$$$.</p><p>Now consider some point $$$s$$$. Consider the half-plane $$$H$$$ of points $$$t$$$ such that the cross product $$$s \wedge t$$$ is positive. For a quadrilateral with $$$s$$$ to contain $$$p$$$, it has to have at least one point from $$$H$$$ and at least one point not from $$$H$$$. Conversely, we will count the number of quadruples $$$(s, t_1, t_2, t_3)$$$ such that $$$t_1, t_2, t_3 \in H$$$. It is just the binomial coefficient $$$|H| \choose 3$$$.</p><p>Now do that for all $$$s$$$ and all corresponding $$$H$$$, in linear time, using the two pointers method.</p><p>With iterating over all $$$p$$$ and sorting, the complexity is $$$O (n^2 \log n)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570783 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570783 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570783"> <li> <div class="comment"> <table class="comment-table" commentId="571005" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLamarca" style="position: relative;"> <img src='https://userpic.codeforces.org/379329/avatar/842836a6a188aadb.jpg'/> </a> <div><a href="/profile/VLamarca" title="Master VLamarca" class="rated-user user-orange">VLamarca</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571005" href="?#comment-571005" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571005" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571005" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="379329" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571005"> <div class="moveup"> <div class="ttypography"><p>This solution works for any size of polygon right? For example if the problem was about triangles instead of quadrilaterals</p><p>thanks for sharing it btw </p></div> </div> </div> <div class="reply info"> <a class="comment-571005 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571005 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571005"> <li> <div class="comment"> <table class="comment-table" commentId="571175" commentParentId="571005"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571175" href="?#comment-571175" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571005" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571175" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571175"> <div class="moveup"> <div class="ttypography"><p>Looks like, yeah, the same argument about all points being in one half-plane would work for pentagons and more.</p><p>Now, if the problem asks for <em>convex</em> polygons, it gets trickier, even with quadrilaterals.</p></div> </div> </div> <div class="reply info"> <a class="comment-571175 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571175 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571175"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571064" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Simurgh" style="position: relative;"> <img src='https://userpic.codeforces.org/1365761/avatar/1d3d3be9bd64e4c9.jpg'/> </a> <div><a href="/profile/Simurgh" title="Expert Simurgh" class="rated-user user-blue">Simurgh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571064" href="?#comment-571064" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571064" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1365761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571064"> <div class="moveup"> <div class="ttypography"><p>Where can I learn more about cross products of vectors and how they can be used in geometry problems?</p></div> </div> </div> <div class="reply info"> <a class="comment-571064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571064"> <li> <div class="comment"> <table class="comment-table" commentId="571178" commentParentId="571064"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571178" href="?#comment-571178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571064" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571178"> <div class="moveup"> <div class="ttypography"><p>Basically, scalar product and cross product are similar in behavior to cosine and sine of angle between vectors, respectively. Their signs behave the same.</p><p>The upside is that, more often than not, we are given coordinates of points as integers (or rationals). And computing scalar and cross products can be done using integers only. So we don't have to resort to floating point and then deal with a whole additional class of errors because of loss of precision.</p><p>As for more general overview, a <a href="https://www.google.com/search?q=scalar+product+and+cross+product+in+computational+geometry">Google search</a> lands some nice articles on the first page.</p></div> </div> </div> <div class="reply info"> <a class="comment-571178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571178"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571093" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 13:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571093" href="?#comment-571093" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571093" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571093" class="CommentVoteFrame" data-commentRating="10" 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: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-571093"> <div class="moveup"> <div class="ttypography"><p>How can I actually easily find the sign of the cross product between two vectors? I got an idea of how to do it with the angle between them, but it seems ugly and probably prone to bugs.</p><p>Edit: I found a way on <a href="https://en.wikipedia.org/wiki/Cross_product#Computational_geometry">Wikipedia</a>, scroll down to the Computation Geometry section.</p></div> </div> </div> <div class="reply info"> <a class="comment-571093 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571093 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571093"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570787" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/undisputedAshu" style="position: relative;"> <img src='https://userpic.codeforces.org/327726/avatar/92b4b2153c6ba4e4.jpg'/> </a> <div><a href="/profile/undisputedAshu" title="Pupil undisputedAshu" class="rated-user user-green">undisputedAshu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570787" href="?#comment-570787" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570787" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="327726" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570787"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain for B</p><p>3</p><p>4 2 0 2 0</p><p>6 9 9 8 8 7 7</p><p>1 6</p><p>how is it 7?</p></div> </div> </div> <div class="reply info"> <a class="comment-570787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570787"> <li> <div class="comment"> <table class="comment-table" commentId="570793" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/djm03178" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/djm03178" title="Master djm03178" class="rated-user user-orange">djm03178</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570793" href="?#comment-570793" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570793" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="687688" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570793"> <div class="moveup"> <div class="ttypography"><p>Let's say a = [2,0,2,0], b = [9,9,8,8,7,7], c = [6], then the answers are: aa, ab, ac, ba, bb, ca, and cb.</p></div> </div> </div> <div class="reply info"> <a class="comment-570793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570793"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570794" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gol_en_05" style="position: relative;"> <img src='https://userpic.codeforces.org/838032/avatar/8167074e5c48a57d.jpg'/> </a> <div><a href="/profile/gol_en_05" title="Specialist gol_en_05" class="rated-user user-cyan">gol_en_05</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570794" href="?#comment-570794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570794" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570794"> <div class="moveup"> <div class="ttypography"><p>since 2 0 2 0 has an ascent.so total pairs are 3. 2 nd sequence does not have an ascent but pairs (2,2),(2,1) has ascent. similarly for 3rd sequence pairs(3,1) and(3,2) has ascent. so total 7 pairs are possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-570794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570794"> <li> <div class="comment"> <table class="comment-table" commentId="570904" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570904" href="?#comment-570904" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570904" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570904"> <div class="moveup"> <div class="ttypography"><p>I'm struggling to understand what does &quot;but pairs (2,2),(2,1) has ascent&quot; mean. Can you please elaborate? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-570904 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570904 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570904"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570916" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570916" href="?#comment-570916" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570916" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570916"> <div class="moveup"> <div class="ttypography"><p>Thanks I got it!</p></div> </div> </div> <div class="reply info"> <a class="comment-570916 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570916 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570916"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570795" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BOGDAN_" 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/BOGDAN_" title="Expert BOGDAN_" class="rated-user user-blue">BOGDAN_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570795" href="?#comment-570795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570795" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="635882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570795"> <div class="moveup"> <div class="ttypography"><p>Let 1, 2, 3 — indexes of arrays. Here is &quot;1 + 2&quot;</p><p>&quot;1 + 3&quot;</p><p>&quot;1 + 1&quot;</p><p>&quot;2 + 2&quot;</p><p>&quot;2 + 1&quot;</p><p>&quot;3 + 1&quot;</p><p>&quot;3 + 2&quot;</p><p>At all — answer 7.</p></div> </div> </div> <div class="reply info"> <a class="comment-570795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570803" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Wa-Automaton" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Wa-Automaton" title="Candidate Master Wa-Automaton" class="rated-user user-violet">Wa-Automaton</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570803" href="?#comment-570803" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570803" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570803" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1365147" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570803"> <div class="moveup"> <div class="ttypography"><p>For D, removing operation is at time ea_i + 1 ?</p><p>UPD: It's fixed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570803 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570803 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570803"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570816" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570816" href="?#comment-570816" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570816" 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="570816" 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-570816"> <div class="moveup"> <div class="ttypography"><p>D can be solved using &quot;Job scheduling &quot; algorithm. Initially we check all the intervals for both the venues individually,whether they overlap,if we get different answer,answer is &quot;NO&quot;.</p><p>If we get same answer and both timings of both venues don't overlap,then answer is &quot;YES&quot;.</p><p>If we get &quot;over-lap&quot; for both,there is a possibility that removing some lectures might make one venue overlapping and other non_overlapping</p><p>eg: 1 2 3 4</p> <pre>3 4 4 5 4 5 6 7</pre><p>In this case,we use job scheduling algorithm to find the largest no of lectures that can be present such that,lecture timings don't overlap for venue A.</p><p>Keep only those lectures for B,check if answer is different for both venues,do the same thing for venue B.</p><p><a href="/contest/1284/submission/68206806" title="Submission 68206806 by AjaySabarish">68206806</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570816 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570816 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570816"> <li> <div class="comment"> <table class="comment-table" commentId="571060" commentParentId="570816"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571060" href="?#comment-571060" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570816" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571060" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571060"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/AjaySabarish" title="Expert AjaySabarish">AjaySabarish</a> Hi, can you please explain the part about &quot;non over-lap&quot; in a little detail?How is there a possibility that removing some lectures might make one venue overlapping and other non_overlapping? I also thought about job scheduling algo but as mentioned in comments, did not consider such cases like finding interval in a and then checking them in b and vice versa. Do they both not give same result? </p></div> </div> </div> <div class="reply info"> <a class="comment-571060 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571060 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571060"> <li> <div class="comment"> <table class="comment-table" commentId="571066" commentParentId="571060"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 11:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571066" href="?#comment-571066" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571060" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571066" 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-571066"> <div class="moveup"> <div class="ttypography"><p>Sry there was a typo,now corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-571066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571066"> <li> <div class="comment"> <table class="comment-table" commentId="571198" commentParentId="571066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571198" href="?#comment-571198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571198"> <div class="moveup"> <div class="ttypography"><p>Still can you explain that point about removing some lectures?</p></div> </div> </div> <div class="reply info"> <a class="comment-571198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571198"> <li> <div class="comment"> <table class="comment-table" commentId="571219" commentParentId="571198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571219" href="?#comment-571219" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571219" 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-571219"> <div class="moveup"> <div class="ttypography"><p>Consider the above example,which I gave </p><p>3</p><p>1 2 3 4</p><p>3 4 4 5</p><p>4 5 6 7</p><p>Now,the timings overlap for both venues,but if you remove lecture 3,timings dont overlap for venue A but overlap for venue B.</p><p>This is the last case which I was talking about,now you have to use job scheduling to find the answer.</p><p>Find the highest number of non overlapping segments for A,it is lecture 1,2.</p><p>Now keep only these lectures for both venues,now the segments for B should also not overlap for &quot;not venue sensitive&quot;. But it is overlapping,so it is venue sensitive</p></div> </div> </div> <div class="reply info"> <a class="comment-571219 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571219 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571219"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570825" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SajidZakaria" style="position: relative;"> <img src='https://userpic.codeforces.org/553136/avatar/f6d8cc00ec65b842.jpg'/> </a> <div><a href="/profile/SajidZakaria" title="Candidate Master SajidZakaria" class="rated-user user-violet">SajidZakaria</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570825" href="?#comment-570825" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570825" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="553136" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570825"> <div class="moveup"> <div class="ttypography"><p>The test cases in D were very &quot;weak&quot;. My solution : <a href="/contest/1284/submission/68205621" title="Submission 68205621 by SajidZakaria">68205621</a></p><p>For very large N, it's enough to only check if each of the lectures have the same number of intersections in A and B. Taking advantage of the fact that it's hard to put up a test case that avoids being fooled that way.</p></div> </div> </div> <div class="reply info"> <a class="comment-570825 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570825 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570825"> <li> <div class="comment"> <table class="comment-table" commentId="634898" commentParentId="570825"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Prajwal_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Prajwal_" title="Expert Prajwal_" class="rated-user user-blue">Prajwal_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/02/2020 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-634898" href="?#comment-634898" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570825" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="634898" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360518" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-634898"> <div class="moveup"> <div class="ttypography"><p>but how will you calculate the intersections in O(n) time.Can you explain once more??</p></div> </div> </div> <div class="reply info"> <a class="comment-634898 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-634898 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-634898"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570829" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570829" href="?#comment-570829" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570829" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570829"> <div class="moveup"> <div class="ttypography"><p>Can you share other solutions to E? Except <a class="rated-user user-orange" href="/profile/Gassa" title="International Master Gassa">Gassa</a>'s (above)</p></div> </div> </div> <div class="reply info"> <a class="comment-570829 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570829 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570829"> <li> <div class="comment"> <table class="comment-table" commentId="570852" commentParentId="570829"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570852" href="?#comment-570852" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570829" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570852" 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="570852" class="CommentVoteFrame" data-commentRating="45" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+45</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570852"> <div class="moveup"> <div class="ttypography"><p>I'll put it short:</p> <ul> <li>(By <a class="rated-user user-red" href="/profile/kdh9949" title="International Grandmaster kdh9949">kdh9949</a> <a class="rated-user user-orange" href="/profile/jihoon" title="International Master jihoon">jihoon</a>) Find $$$f(p)$$$ for each point. You can see that the set can enclose $$$p$$$ iff its convex hull contains $$$p$$$. Checking the containment is hard, so sort by angle, and eliminate the set that does not contain $$$p$$$, which reduces to almost similar sweep with model code. I think this is the easiest solution to come up with.</li> <li>(By <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a>) The answer depends on the 2 * (number of convex quadrilaterals) + (number of concave quadrilaterals). We denote this number $$$A$$$. I think the answer is $$$(A - 2\binom{n}{4}) \times (n-4)/2$$$, or something like that. This problem is bit harder, so you need another type of angular sweep like JOI Open 2017 Bulldozer. I think this is more involved to code, but our great tester <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a> took exactly 12 minutes to AC this.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-570852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570852"> <li> <div class="comment"> <table class="comment-table" commentId="571006" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/NoLongerRed" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/NoLongerRed" title="Grandmaster NoLongerRed" class="rated-user user-red">NoLongerRed</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571006" href="?#comment-571006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571006" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="567645" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571006"> <div class="moveup"> <div class="ttypography"><p>My solution is pretty much the same as molamola's solution and I think it is not necessary to do a cool angular sweep:<br />Let $$$X$$$ be the number of $$$((A,B,C),D)$$$ such that $$$D$$$ lies in $$$ABC$$$ and $$$(A,B,C)$$$ is an unordered tuple. The answer is $$$(n-4)X/2$$$.<br />$$$X$$$ can be counted easily: fixing $$$D$$$ and sort other points by the angles, then do a bunch of lower bound.</p></div> </div> </div> <div class="reply info"> <a class="comment-571006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571006"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571012" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571012" href="?#comment-571012" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571012" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571012"> <div class="moveup"> <div class="ttypography"><p>Thanks for sharing. The solution in Editorial really beautiful, but I don't know. Is that possible to came up with such solution in ~1 hour?</p></div> </div> </div> <div class="reply info"> <a class="comment-571012 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571012 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571012"> <li> <div class="comment"> <table class="comment-table" commentId="571014" commentParentId="571012"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571014" href="?#comment-571014" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571012" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571014" 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="571014" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571014"> <div class="moveup"> <div class="ttypography"><p>Actually my solution submitted during the contest is exactly same as the tutorial solution. In fact, I tried to compute all of $$$x$$$, $$$y$$$, and $$$z$$$, so I double-counted not only the edges of the convex hull but also the diagonal edges, to obtain three linear equations.</p> <center>$$$ x + y + z = {n \choose 5} \\ 5x + 4y + 3z = sth \\ 5x + 6y + 7z = sth $$$</center><p>Unfortunately, this linear system was undetermined, and all I can get was $$$(y + 2z)$$$. That was when I felt quite disappointed. But surprisingly, the answer to the problem happened to be exactly $$$(y + 2z)$$$, so I could finally solve the problem.</p><p>At first, I thought I was lucky enough to find a solution with such unsolvable system. So I headed to this tutorial to read the &quot;official&quot; solution, only to find my solution again. Thanks to your question, I found it in the comments :-)</p><p><a href="/contest/1284/submission/68196878" title="Submission 68196878 by jo_on">68196878</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571014 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571014 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571014"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570830" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570830" href="?#comment-570830" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570830" class="CommentVoteFrame" data-commentRating="3" 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: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-570830"> <div class="moveup"> <div class="ttypography"><p>Just curious,did everyone who solved C in contest,prove the solution?It was not so obvious to me,deciphering and processing what a &quot;framed segment&quot; is,took a lot of time.</p><p>Finding pattern was quite difficult,as manually generating test case even for n=4 is difficult</p><p>Lot of people solved it,is there any other idea?</p></div> </div> </div> <div class="reply info"> <a class="comment-570830 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570830 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570830"> <li> <div class="comment"> <table class="comment-table" commentId="570899" commentParentId="570830"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570899" href="?#comment-570899" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570830" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570899" class="CommentVoteFrame" data-commentRating="2" 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:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570899"> <div class="moveup"> <div class="ttypography"><p>Hi, If you now know what a &quot;framed segment&quot; is, then try to formulate number of &quot;framed segment&quot; of a particular length for a given n. For example: if we want to count &quot;framed segement&quot; of length 1. Let's first consider all &quot;framed segment&quot; containing only digit 1. For this &quot;framed segment&quot; to be at leftmost, there are (n — 1)! permutations. Similar argument goes for its other positions as well. This gives us count : (n — 1)! * n. Now, there are total of n single digits like &quot;1&quot; which can make single length &quot;framed segement&quot;. Thus now count for all single length &quot;framed segement&quot; is : (n — 1)! * n * n (something missing?). I have tried to explain the solution with single length fragment above with some details missing which I think you will figure out. Please try to come-up with a general formulation for any &quot;framed segment&quot;length x for a given n. Summing it all up will give you the answer. Link to my submission : <a href="https://codeforces.com/contest/1284/submission/68187501">Here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570899 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570899 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570899"> <li> <div class="comment"> <table class="comment-table" commentId="570912" commentParentId="570899"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570912" href="?#comment-570912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570899" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570912" 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-570912"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot,I get the solution,but I am just curious about the high number of submissions,was it so obvious?did everyone actually prove it or used their intuition to get it?</p></div> </div> </div> <div class="reply info"> <a class="comment-570912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570912"> <li> <div class="comment"> <table class="comment-table" commentId="570917" commentParentId="570912"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570917" href="?#comment-570917" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570912" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570917" 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-570917"> <div class="moveup"> <div class="ttypography"><p>I guess that depends on one's way of counting up to the answer. And from the number of submissions, it feels like people are actually good at counting..:P</p></div> </div> </div> <div class="reply info"> <a class="comment-570917 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570917 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570917"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kiimak" style="position: relative;"> <img src='https://userpic.codeforces.org/780779/avatar/9d6b81e1dd625cd6.jpg'/> </a> <div><a href="/profile/kiimak" title="Candidate Master kiimak" class="rated-user user-violet">kiimak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570849" href="?#comment-570849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570849" 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="570849" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="780779" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570849"> <div class="moveup"> <div class="ttypography"><p>Hi, I think I found a test case for problem D where my solution gets accepted but it should be incorrect.</p> <pre><code>5 1 10 1 10 2 20 11 30 11 30 2 20 21 40 21 40 31 50 31 50 </code></pre><p>I've checked with the code given in the tutorial, the answer is NO, but my solution gives YES. <a href="/contest/1284/submission/68207409" title="Submission 68207409 by kiimak">68207409</a></p><p>I've modeled it as a graph and put an edge (u, v) if lecture u and v meet. I thought it would be enough to check two things for graph A and B (venue A and B)</p> <ul> <li>the number of degrees for each lecture</li> <li>the lecture set of each component</li> </ul><p>I've submitted it after the contest so it doesn't effect my ratings, but I thought it was worth mentioning.</p></div> </div> </div> <div class="reply info"> <a class="comment-570849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570849"> <li> <div class="comment"> <table class="comment-table" commentId="570891" commentParentId="570849"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ormlis" style="position: relative;"> <img src='https://userpic.codeforces.org/1250517/avatar/5b32008c179f4f98.jpg'/> </a> <div><a href="/profile/Ormlis" title="Legendary Grandmaster Ormlis" class="rated-user user-legendary"><span class="legendary-user-first-letter">O</span>rmlis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570891" href="?#comment-570891" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570891" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1250517" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570891"> <div class="moveup"> <div class="ttypography"><p>I made the same mistake. I tried to find a test case where this is not true, but I could not. Thanks you</p></div> </div> </div> <div class="reply info"> <a class="comment-570891 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570891 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570891"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DJoker99" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/DJoker99" title="Pupil DJoker99" class="rated-user user-green">DJoker99</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570865" href="?#comment-570865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570865" 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="570865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="886083" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570865"> <div class="moveup"> <div class="ttypography"><p>Solution for B [Best :- O(n) Worst :- O(nlogn)]</p><p><a href="https://codeforces.com/contest/1284/submission/68210022">https://codeforces.com/contest/1284/submission/68210022</a></p><p>The condition for a non-ascent sequence a and a non-ascen sequence b to form an ascenting sequence is</p><p><code>min(a) &lt;max(b)</code></p> <ol> <li>First traverse the lists and store max and min in two separate vectors.</li> <li>if a sequence has ascent ie if an element greater than current min or current max occurs then that sequence will always give an ascenting sequence hence do <code>cnt = cnt + 2*n-1</code> <code>n--;</code> because that sequence will form 2n-1 sequences on concatenation</li> <li><p>Sort the max and min vectors then use two pointer approach.</p></li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-570865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570865"> <li> <div class="comment"> <table class="comment-table" commentId="570973" commentParentId="570865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 00:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570973" href="?#comment-570973" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570865" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570973" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570973" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570973"> <div class="moveup"> <div class="ttypography"><p>Involving sort gives already nlogn solution) - <a href="https://codeforces.com/contest/1284/submission/68206308">my code</a> — P. S. I have similar solution, but simpler.</p></div> </div> </div> <div class="reply info"> <a class="comment-570973 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570973 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570973"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570877" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prateek_aries" style="position: relative;"> <img src='https://userpic.codeforces.org/780171/avatar/c6136d0edef16466.jpg'/> </a> <div><a href="/profile/prateek_aries" title="Expert prateek_aries" class="rated-user user-blue">prateek_aries</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570877" href="?#comment-570877" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570877" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="780171" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570877"> <div class="moveup"> <div class="ttypography"><p>Someone please explain me the meaning of the last statement in C. &quot;By observing that there exist exactly n−len+1 pairs with 1≤l≤r≤n,r−l+1=len, we can simply multiply this number for each length, giving a O(n) time solution.&quot; Please give any example.</p></div> </div> </div> <div class="reply info"> <a class="comment-570877 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570877 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570877"> <li> <div class="comment"> <table class="comment-table" commentId="570981" commentParentId="570877"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570981" href="?#comment-570981" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570877" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570981" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570981"> <div class="moveup"> <div class="ttypography"><p>Example of what is it about: </p><p>Consider n of 5 and len of 3</p> <ul> <li><p>1 2 3</p></li> <li><p>2 3 4</p></li> <li><p>3 4 5</p></li> </ul><p>Permutate each of them, and you will get all framed subarrays for n and len of the example. </p></div> </div> </div> <div class="reply info"> <a class="comment-570981 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570981 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570981"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570883" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/im_sanyam" style="position: relative;"> <img src='https://userpic.codeforces.org/605247/avatar/6943d67eaf1d4243.jpg'/> </a> <div><a href="/profile/im_sanyam" title="Expert im_sanyam" class="rated-user user-blue">im_sanyam</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570883" href="?#comment-570883" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570883" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="605247" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570883"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain to me the solution of problem C in a better and intuitive way?</p></div> </div> </div> <div class="reply info"> <a class="comment-570883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570883"> <li> <div class="comment"> <table class="comment-table" commentId="570902" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570902" href="?#comment-570902" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570902" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570902" 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-570902"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570902 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570902 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570902"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570911" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/meiniak" style="position: relative;"> <img src='https://userpic.codeforces.org/803808/avatar/924fee722719da18.jpg'/> </a> <div><a href="/profile/meiniak" title="Newbie meiniak" class="rated-user user-gray">meiniak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570911" href="?#comment-570911" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570911" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="803808" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570911"> <div class="moveup"> <div class="ttypography"><p>let's take n = 5. ar = [1,2,3,4,5] . Now iterate for all possible length of sub-array and count number of good sub-array for that length. k = 1, 2, 3 and so on.</p><p>let take say k = 2 and n = 5. So there are n-k+1 position possible to place k elements i.e If we consider [1,2] then we can place [1,2] in position _ 3 _ 4 _ 5 _ and you can select (n-k+1) elements from n elements to i.e [1,2] , [2,3] , [3,4] and [4,5] . So this is how we got (n-k+1) * (n-k+1) and now we just have to count number of possible permutation of k and (n-k) elements left which is nothing but k! and (n-k)! .** (n-k+1) * (n-k+1) * k! * (n-k)!** is the total answer</p></div> </div> </div> <div class="reply info"> <a class="comment-570911 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570911 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570911"> <li> <div class="comment"> <table class="comment-table" commentId="647624" commentParentId="570911"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lazy_learner" style="position: relative;"> <img src='https://userpic.codeforces.org/926934/avatar/1c97e4ddf06e9813.jpg'/> </a> <div><a href="/profile/lazy_learner" title="Newbie lazy_learner" class="rated-user user-gray">lazy_learner</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2020 08:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-647624" href="?#comment-647624" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570911" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="647624" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926934" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-647624"> <div class="moveup"> <div class="ttypography"><p>But would that not lead to overcounting.<br />Consider the case 3 (1 2) 4 5 and 3 1 2 (4 5).<br />These 2 permutations are same and will be counted twice, once when we consider 1,2 together and second when 4,5 are taken together.</p></div> </div> </div> <div class="reply info"> <a class="comment-647624 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-647624 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-647624"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570914" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rover1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rover1" title="Specialist rover1" class="rated-user user-cyan">rover1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570914" href="?#comment-570914" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570914" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1239447" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570914"> <div class="moveup"> <div class="ttypography"><p>If in question C, we have given a permutation of length n then we need to find happiness... Anyone want to share their approaches ..</p></div> </div> </div> <div class="reply info"> <a class="comment-570914 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570914 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570914"> <li> <div class="comment"> <table class="comment-table" commentId="570918" commentParentId="570914"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570918" href="?#comment-570918" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570914" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570918" 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-570918"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570918"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570927" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/M1v1savva1601" style="position: relative;"> <img src='https://userpic.codeforces.org/539005/avatar/21949389dc808e09.jpg'/> </a> <div><a href="/profile/M1v1savva1601" title="Master M1v1savva1601" class="rated-user user-orange">M1v1savva1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570927" href="?#comment-570927" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570927" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="539005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570927"> <div class="moveup"> <div class="ttypography"><p>Shouldn't it be <strong>eai + 1</strong> in D tutorial?</p></div> </div> </div> <div class="reply info"> <a class="comment-570927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570927"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570941" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AwakeAnay" style="position: relative;"> <img src='https://userpic.codeforces.org/666008/avatar/7043fde46ee0493c.jpg'/> </a> <div><a href="/profile/AwakeAnay" title="Grandmaster AwakeAnay" class="rated-user user-red">AwakeAnay</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 23:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570941" href="?#comment-570941" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="666008" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570941"> <div class="moveup"> <div class="ttypography"><p>I had a overkill solution for $$$D$$$ which led to a good data structures problem. While, others have provided much more elegant solutions, this reduced version is a good problem on its own and worth sharing.</p><p>Here's the problem:</p><p>You are given two sequences $$$a_i$$$ and $$$b_i$$$ of length $$$2N$$$ each. Each number from $$$1$$$ to $$$N$$$ appears exactly twice in both the sequences. You have to solve $$$Q$$$ queries of the following kind:</p><p>Given $$$l$$$, $$$r$$$, $$$x$$$ and $$$y$$$, find the set of distinct elements in $$$(l, r)$$$ in $$$a$$$ is exactly equal to the set of distinct elements in $$$(x, y)$$$ in $$$b$$$. That is, any number $$$u$$$ has an appearance in segment $$$(l, r)$$$ in $$$a$$$ if and only if it has an appearance in segment $$$(x, y)$$$ in $$$b$$$. Try to solve this online in $$$O((N+Q)\log(N))$$$.</p><p>Think of how you can reduce today's $$$D$$$ into this problem.</p><p>My code for today's D: <a href="/contest/1284/submission/68189310" title="Submission 68189310 by AwakeAnay">68189310</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570941"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570975" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/madhav_1999" style="position: relative;"> <img src='https://userpic.codeforces.org/594602/avatar/cad96e04d2a42e66.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/madhav_1999" title="Master madhav_1999" class="rated-user user-orange">madhav_1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570975" href="?#comment-570975" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570975" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="594602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570975"> <div class="moveup"> <div class="ttypography"><p>In D: &quot;Event removing interval [sbi, ebi] from S at time ebi+1.&quot;</p><p><a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a>, I think you made an error here, it should be eai + 1 instead</p></div> </div> </div> <div class="reply info"> <a class="comment-570975 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570975 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570975"> <li> <div class="comment"> <table class="comment-table" commentId="571032" commentParentId="570975"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571032" href="?#comment-571032" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570975" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571032" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571032"> <div class="moveup"> <div class="ttypography"><p>Sorry, fixed. </p></div> </div> </div> <div class="reply info"> <a class="comment-571032 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571032 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571032"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570982" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 02:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570982" href="?#comment-570982" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570982" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570982"> <div class="moveup"> <div class="ttypography"><p>Problem B can also be solved in $$$O(n)$$$. Be $$$asc$$$ the number of sequences that have an ascent. For each sequence, check if it's non-increasing. If it isn't any concatenation we do will have an ascent, so we can add $$$n$$$ to our answer and $$$1$$$ to $$$asc$$$. Now be $$$s$$$ a non-increasing sequence and let's set it as the right part of the concatenation. We will only have an ascent in the concatenation if the left part already has an ascent or has an element smaller than any element in $$$s$$$, specially it's maximum. We have $$$asc$$$ sequences of the first type, so that's easy, and for the second part we can precalculate it by creating an array $$$minfreq$$$ where we store the minimum of each non-increasing sequence in it's position (as $$$s_{i,j} &lt; 10^6$$$) and do a sweep from $$$1$$$ to $$$10^6$$$ to accumulate our sum ($$$minfreq[i] = minfreq[i-1] +minfreq[i]$$$). Now we have our answer for the second part in position $$$minfreq[max(s)-1]$$$, and we can just add both parts to our answer. Since we can precalculate $$$minfreq$$$, $$$max(s)$$$ and $$$asc$$$ in $$$O(n)$$$ and the answer can be calculated in $$$O(1)$$$ using our precalculations total complexity is $$$O(n)$$$ </p></div> </div> </div> <div class="reply info"> <a class="comment-570982 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570982 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570982"> <li> <div class="comment"> <table class="comment-table" commentId="570987" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dblark" style="position: relative;"> <img src='https://userpic.codeforces.org/693276/avatar/70323ef41e4c9add.jpg'/> </a> <div><a href="/profile/dblark" title="International Master dblark" class="rated-user user-orange">dblark</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 03:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570987" href="?#comment-570987" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570987" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="693276" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570987"> <div class="moveup"> <div class="ttypography"><p>Yeah, the same idea with you!</p></div> </div> </div> <div class="reply info"> <a class="comment-570987 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570987 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570987"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571037" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 08:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571037" href="?#comment-571037" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571037" class="CommentVoteFrame" data-commentRating="0" 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:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571037"> <div class="moveup"> <div class="ttypography"><p>I did the same, but this is not O(N). The time Complexity will be O(n + maxELE) where maxELE is the largest sequence element seen in input.</p><p>We were lucky that the constraint on that wasn't 10^9.</p><p>Also consider cases in which n = 5 but the elements are still very large, our code would still take lot of time to execute.</p></div> </div> </div> <div class="reply info"> <a class="comment-571037 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571037 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571037"> <li> <div class="comment"> <table class="comment-table" commentId="571654" commentParentId="571037"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 18:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571654" href="?#comment-571654" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571037" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571654" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571654"> <div class="moveup"> <div class="ttypography"><p>Yeah that's true, the editorial's solution is more general for that same reason</p></div> </div> </div> <div class="reply info"> <a class="comment-571654 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571654 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571654"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571551" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571551" href="?#comment-571551" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571551" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571551"> <div class="moveup"> <div class="ttypography"><p>I cant understand the minfreq[i]=minfreq[i−1]+minfreq[i] . can you explain me </p></div> </div> </div> <div class="reply info"> <a class="comment-571551 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571551 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571551"> <li> <div class="comment"> <table class="comment-table" commentId="571653" commentParentId="571551"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571653" href="?#comment-571653" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571551" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571653" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571653"> <div class="moveup"> <div class="ttypography"><p>It's called accumulated sum. Basically we want minfreq[i] to be the frequency of all numbers $$$\leq$$$ to i, so we need to push our previous array position to our current one, so that we also take into account the occurences of numbers &lt; i, and not just equal to i</p></div> </div> </div> <div class="reply info"> <a class="comment-571653 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571653 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571653"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571001" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Aguin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Aguin" title="Candidate Master Aguin" class="rated-user user-violet">Aguin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571001" href="?#comment-571001" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571001" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="297931" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571001"> <div class="moveup"> <div class="ttypography"><p>How to count different quadrilaterals in problem E?</p></div> </div> </div> <div class="reply info"> <a class="comment-571001 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571001 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571001"> <li> <div class="comment"> <table class="comment-table" commentId="571004" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571004" href="?#comment-571004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571004"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571004"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571007" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 05:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571007" href="?#comment-571007" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571007" class="CommentVoteFrame" data-commentRating="3" 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;">+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-571007"> <div class="moveup"> <div class="ttypography"><p>For example, for each pair of points $$$(i, j)$$$, we can find the number of points on one side of the line i-j ($$$a$$$), the number of points on the other side ($$$N-2-a$$$), sum that up, divide by 2 and subtract $$$2{N\choose 4}$$$. Why? For each 4-tuple of points, if one of them is inside the triangle formed by the other 3 (their convex hull is a triangle), we get 3 lines (inner point, some other point) that are counted here, and when their convex hull is a quadrilateral, we get 2 such lines — its diagonals; we subtract (2 * number of 4-tuples) to get the number of 4-tuples where one point is inside.</p><p>How to find these $$$a$$$ for each pair $$$(i, j)$$$ fast? Let's say that $$$i$$$ is fixed, sort all remaining points by their angle around point $$$i$$$, then consider a line that crosses $$$i$$$, start rotating it and whenever it crosses one of these points, update the current value of $$$a$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-571007 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571007 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571007"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571011" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571011" href="?#comment-571011" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571011" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571011"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> (<a href="/topic/73334/en9">previous revision</a>, <a href="/topic/73334/en10">new revision</a>, <a href="/topic/73334/diff/en9/en10">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-571011 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571011 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571011"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hd7" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Hd7" title="Specialist Hd7" class="rated-user user-cyan">Hd7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571018" href="?#comment-571018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571018" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="559666" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571018"> <div class="moveup"> <div class="ttypography"><p>Could anyone give me a more elaborated explanation for problem D, I didn't grasp the editorial at all.</p></div> </div> </div> <div class="reply info"> <a class="comment-571018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571031" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571031" href="?#comment-571031" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571031" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571031"> <div class="moveup"> <div class="ttypography"><p>Expected a matroid problem, as <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> took matroid class last semester XD</p></div> </div> </div> <div class="reply info"> <a class="comment-571031 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571031 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571031"> <li> <div class="comment"> <table class="comment-table" commentId="571033" commentParentId="571031"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571033" href="?#comment-571033" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571031" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571033" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571033"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/team/65651">matroid fan club!</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571033 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571033 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571033"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571040" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PouyaNavid" style="position: relative;"> <img src='https://userpic.codeforces.org/670316/avatar/c42e949ea38011da.jpg'/> </a> <div><a href="/profile/PouyaNavid" title="Master PouyaNavid" class="rated-user user-orange">PouyaNavid</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 09:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571040" href="?#comment-571040" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571040" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="670316" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571040"> <div class="moveup"> <div class="ttypography"><p>Hack Test for D <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a></p><p>4 1 10 51 60 2 20 44 52 3 40 43 45 42 45 50 50</p></div> </div> </div> <div class="reply info"> <a class="comment-571040 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571040 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571040"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571088" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hazyknight" style="position: relative;"> <img src='https://userpic.codeforces.org/537474/avatar/e2c88ee4c2562699.jpg'/> </a> <div><a href="/profile/Hazyknight" title="International Grandmaster Hazyknight" class="rated-user user-red">Hazyknight</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571088" href="?#comment-571088" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571088" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571088" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="537474" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571088"> <div class="moveup"> <div class="ttypography"><p>Actually, Problem G can be solved easily by matroid intersection. Consider two matroid M1(S,I),M2(S,I), S is the set of wall, M1 is a graph matroid , M2 is a matroid which any black cell has at least to side without wall. Code: <a href="https://codeforces.com/contest/1284/submission/68215804">https://codeforces.com/contest/1284/submission/68215804</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571088 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571088 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571088"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571128" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amstan" style="position: relative;"> <img src='https://userpic.codeforces.org/734003/avatar/344c500da9a98a7f.jpg'/> </a> <div><a href="/profile/amstan" title="Expert amstan" class="rated-user user-blue">amstan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571128" href="?#comment-571128" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571128" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="734003" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571128"> <div class="moveup"> <div class="ttypography"><p>Is there anyone who solved D using coordinate compression and prefix sum ? If so, could you please share your submission.</p></div> </div> </div> <div class="reply info"> <a class="comment-571128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571128"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571138" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HaoxuanXIE" style="position: relative;"> <img src='https://userpic.codeforces.org/1234114/avatar/fa4b56dfead7992e.jpg'/> </a> <div><a href="/profile/HaoxuanXIE" title="Expert HaoxuanXIE" class="rated-user user-blue">HaoxuanXIE</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571138" href="?#comment-571138" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571138" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1234114" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571138"> <div class="moveup"> <div class="ttypography"><p>Why does D need to check in two directions? If I check in one direction, I get wrong answer at 9th point. But I think it is appropriate to check in only one direction.</p></div> </div> </div> <div class="reply info"> <a class="comment-571138 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571138 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571138"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571145" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheeLooser" style="position: relative;"> <img src='https://userpic.codeforces.org/448032/avatar/d5dcfa8c5dbd255f.jpg'/> </a> <div><a href="/profile/TheeLooser" title="Expert TheeLooser" class="rated-user user-blue">TheeLooser</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571145" href="?#comment-571145" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571145" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="448032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571145"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> may as well check how many visits were made to <a href="https://codeforces.com/problemset/problem/1146/H">this</a> page and later to <a href="https://codeforces.com/blog/entry/66639">this</a> page in contest time</p></div> </div> </div> <div class="reply info"> <a class="comment-571145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571145"> <li> <div class="comment"> <table class="comment-table" commentId="571459" commentParentId="571145"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 22:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571459" href="?#comment-571459" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571145" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571459" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571459"> <div class="moveup"> <div class="ttypography"><p>How does that problem help?</p></div> </div> </div> <div class="reply info"> <a class="comment-571459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571459"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571509" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Petr" style="position: relative;"> <img src='https://userpic.codeforces.org/664/avatar/a113c1791cdcd2e1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Petr" title="Legendary Grandmaster Petr" class="rated-user user-legendary"><span class="legendary-user-first-letter">P</span>etr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 01:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571509" href="?#comment-571509" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571509" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="664" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571509"> <div class="moveup"> <div class="ttypography"><p>Re: &quot;Hopefully, the first 80 tests were good enough for the contest.&quot;</p><p>My <a href="https://codeforces.com/contest/1284/submission/68208450">random solution</a> fails on test 87 :) Great job making the tests indeed!</p></div> </div> </div> <div class="reply info"> <a class="comment-571509 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571509 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571509"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571522" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MubtasimShahriar" style="position: relative;"> <img src='https://userpic.codeforces.org/756984/avatar/9113baa4abf04299.jpg'/> </a> <div><a href="/profile/MubtasimShahriar" title="Pupil MubtasimShahriar" class="rated-user user-green">MubtasimShahriar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 05:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571522" href="?#comment-571522" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571522" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756984" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571522"> <div class="moveup"> <div class="ttypography"><p>In Problem D, why does this solution not work? My Solutions is this.</p><p>Sort lectures according to their start-ending time in both venue, Then decide every lecture if it intersects with others in their own venue.</p><p>If there is at least one lecture that make difference in intersecting in both venue, then Subset can not be made. So the answer is no. If every problem either intersects in both venue or does not intersect in both venue then answer is yes. Here is my implementation <a href="/contest/1284/submission/68294866" title="Submission 68294866 by MubtasimShahriar">68294866</a></p><p>Please someone enlighten me where I am misunderstanding.</p></div> </div> </div> <div class="reply info"> <a class="comment-571522 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571522 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571522"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571546" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SLIMSHADYNICK" style="position: relative;"> <img src='https://userpic.codeforces.org/598862/avatar/7629f1b29f0fe807.jpg'/> </a> <div><a href="/profile/SLIMSHADYNICK" title="Candidate Master SLIMSHADYNICK" class="rated-user user-violet">SLIMSHADYNICK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571546" href="?#comment-571546" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571546" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-13" data-commentUserId="598862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-571546"> <div class="moveup"> <div class="ttypography"><p>In problem D, I got wrong answer on test case 14. Can somebody please help.</p></div> </div> </div> <div class="reply info"> <a class="comment-571546 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571546 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571546"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572491" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ftiasch" style="position: relative;"> <img src='https://userpic.codeforces.org/506/avatar/c52be21fbeb4a450.jpg'/> </a> <div><a href="/profile/ftiasch" title="International Grandmaster ftiasch" class="rated-user user-red">ftiasch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/11/2020 00:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572491" href="?#comment-572491" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572491" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="506" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-572491"> <div class="moveup"> <div class="ttypography"><p>2020 begins with two matroid problems. XD</p><p>btw, Challenge in Problem F is called Strong Basis Exchange as in <a href="https://math.mit.edu/~goemans/18438F09/lec11.pdf">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-572491 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572491 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572491"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572780" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Akash79" style="position: relative;"> <img src='https://userpic.codeforces.org/776725/avatar/700a28ac96121584.jpg'/> </a> <div><a href="/profile/Akash79" title="Expert Akash79" class="rated-user user-blue">Akash79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 16:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572780" href="?#comment-572780" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572780" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="776725" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572780"> <div class="moveup"> <div class="ttypography"><p>I am not able to understand problem B's solution.. can anyone please help me out..??</p></div> </div> </div> <div class="reply info"> <a class="comment-572780 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572780 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572780"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 17:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572849" href="?#comment-572849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="572849" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="572849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572849"> <div class="moveup"> <div class="ttypography"><p>Why don't we have to consider the case when there's some period intersecting in A and not intersecting in B? Doesn't that mean that sometimes our code will say 'YES' but the answer is 'NO'. Why? <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a>. EDIT: Ok, I just didn't notice the part of the code where he does the same thing but reversed.</p></div> </div> </div> <div class="reply info"> <a class="comment-572849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572849"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572863" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 18:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572863" href="?#comment-572863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572863" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572863"> <div class="moveup"> <div class="ttypography"><p>What is the hash approach for the problem D?</p></div> </div> </div> <div class="reply info"> <a class="comment-572863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572863"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="576477" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anaksoleh" style="position: relative;"> <img src='https://userpic.codeforces.org/1170460/avatar/27d790d7abbbd3d9.jpg'/> </a> <div><a href="/profile/anaksoleh" title="Newbie anaksoleh" class="rated-user user-gray">anaksoleh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/30/2020 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576477" href="?#comment-576477" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576477" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170460" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-576477"> <div class="moveup"> <div class="ttypography"><p>there is a proof for C solution ?</p></div> </div> </div> <div class="reply info"> <a class="comment-576477 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576477 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576477"> <li> <div class="comment"> <table class="comment-table" commentId="673042" commentParentId="576477"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/XORring-Samurai" style="position: relative;"> <img src='https://userpic.codeforces.org/1384228/avatar/d0258d5ed6604923.jpg'/> </a> <div><a href="/profile/XORring-Samurai" title="Candidate Master XORring-Samurai" class="rated-user user-violet">XORring-Samurai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/02/2020 09:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-673042" href="?#comment-673042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-576477" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="673042" 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="673042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1384228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-673042"> <div class="moveup"> <div class="ttypography"><p>Here is something, that I could think of.</p><p>For each permutation, we have the same $$$r-l$$$. This value varies from $$$0$$$ to $$$n-1$$$ for all $$$n$$$. Now let us consider $$$r-l=d$$$, as a general case. </p><p>For each $$$n$$$, we have $$$n-d$$$ pairs of $$$[l, r]$$$, where $$$r-l=d$$$. Also for all numbers from $$$1$$$ to $$$n$$$, we have $$$n-d$$$ pairs of type $$$[i, j]$$$ such that $$$j-i=d$$$. </p><p>For a segment to be framed, all the other places for each $$$[l, r]$$$ must be occupied by each integer from $$$[i, j]$$$. Therefore, we have $$$d+1$$$ numbers to be arranged in this interval $$$[l, r]$$$ and $$$n-d-1$$$ to be arranged in $$$[1, l-1]$$$ and $$$[r+1, n]$$$. This can be done in $$$(d+1)! * (n-d-1)!$$$ ways. </p><p>But we have $$$n-d$$$ pairs of $$$[l, r]$$$ and $$$n-d$$$ pairs of $$$[i, j]$$$, each of which can occupy this segment. Therefore the answer becomes summation over all $$$d$$$ from $$$0$$$ to $$$n-1$$$: $$$ans = ans + (n-d) * (n-d) * (d+1)! * (n-d-1)!$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-673042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-673042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-673042"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606852" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ThakurSaab" style="position: relative;"> <img src='https://userpic.codeforces.org/1267713/avatar/7c6c4d7b58cddb96.jpg'/> </a> <div><a href="/profile/ThakurSaab" title="Expert ThakurSaab" class="rated-user user-blue">ThakurSaab</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 17:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606852" href="?#comment-606852" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606852" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1267713" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606852"> <div class="moveup"> <div class="ttypography"><p>In problem C , do we consider that the numbers inside a particular segment [l,r] could be different such that, max-min = r-l</p></div> </div> </div> <div class="reply info"> <a class="comment-606852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606852"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="689589" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 07:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689589" href="?#comment-689589" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689589" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689589"> <div class="moveup"> <div class="ttypography"><p>In Problem D I added elements in the segment tree in the decreasing order of eai and then I queried for the previous range if the min of the ls and the maxr intersect with the particular index of a I am addding . I am getting a WA at Test Case 7 for this submission.</p><p>This is my submission link: <a href="https://codeforces.com/contest/1284/submission/91535000">https://codeforces.com/contest/1284/submission/91535000</a></p><p>Can somebody help me with this solution where I went wrong? </p><p>Or is there anyway I can look at the whole testcase then please reply here about how can I do that?</p></div> </div> </div> <div class="reply info"> <a class="comment-689589 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689589 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689589"> <li> <div class="comment"> <table class="comment-table" commentId="689595" commentParentId="689589"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 08:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689595" href="?#comment-689595" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-689589" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689595" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689595"> <div class="moveup"> <div class="ttypography"><p>Never Mind I made a silly typo in the cmp2 function.</p></div> </div> </div> <div class="reply info"> <a class="comment-689595 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689595 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689595"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="722358" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tanishq_code_c" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tanishq_code_c" title="Expert tanishq_code_c" class="rated-user user-blue">tanishq_code_c</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/17/2020 17:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-722358" href="?#comment-722358" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="722358" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1484322" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-722358"> <div class="moveup"> <div class="ttypography"><p>Hi, I am not able to understand the editorial for problem C. can anyone break it down in easy way please ? </p></div> </div> </div> <div class="reply info"> <a class="comment-722358 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-722358 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-722358"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="736312" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheOneYouWant" style="position: relative;"> <img src='https://userpic.codeforces.org/628619/avatar/c785428bde285c3.jpg'/> </a> <div><a href="/profile/TheOneYouWant" title="Master TheOneYouWant" class="rated-user user-orange">TheOneYouWant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/23/2020 05:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-736312" href="?#comment-736312" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="736312" class="CommentVoteFrame" data-commentRating="91" data-commentUserId="628619" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+91</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-736312"> <div class="moveup"> <div class="ttypography"><p>Hello, this seems to be broken (perhaps a sign of how the year 2020 has been so far)</p></div> </div> </div> <div class="reply info"> <a class="comment-736312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-736312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-736312"> <li> <div class="comment"> <table class="comment-table" commentId="737407" commentParentId="736312"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/27/2020 09:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-737407" href="?#comment-737407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-736312" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="737407" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-737407"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> please take a look, thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-737407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-737407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-737407"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741444" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/butterflies" style="position: relative;"> <img src='https://userpic.codeforces.org/1651561/avatar/33dfc9c16e5795ad.jpg'/> </a> <div><a href="/profile/butterflies" title="Specialist butterflies" class="rated-user user-cyan">butterflies</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741444" href="?#comment-741444" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="741444" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="741444" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1651561" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741444"> <div class="moveup"> <div class="ttypography"><p>This question relates to <a href="https://codeforces.com/contest/1284/problem/B">problem B</a>. I have a question with the second example input. Here is the input:</p> <pre><code>3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 </code></pre><p>I believe all arrays have an ascent. In the first array, the pair $$$(i, j) = (3, 4)$$$ works. ($$$a_3 = 0, a_4 = 2.$$$) In the second array, the pair $$$(i, j) = (1, 2)$$$ works. ($$$a_1 = 6, a_2 = 9.$$$) In the third array, the pair $$$(i,j) = (1, 2)$$$ works. ($$$a_1 = 1, a_2 = 6.$$$)</p><p>Thus, shouldn't all pairs of arrays in this case work? There are $$$9$$$ such pairs, but the answer to this should be $$$7.$$$ What is wrong with my reasoning here?</p></div> </div> </div> <div class="reply info"> <a class="comment-741444 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741444 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741444"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741445" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/beetroot" style="position: relative;"> <img src='https://userpic.codeforces.org/1503072/avatar/6668dbf5be4e4495.jpg'/> </a> <div><a href="/profile/beetroot" title="Expert beetroot" class="rated-user user-blue">beetroot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741445" href="?#comment-741445" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741445" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1503072" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741445"> <div class="moveup"> <div class="ttypography"><p>Editorials that didn't age well...</p></div> </div> </div> <div class="reply info"> <a class="comment-741445 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741445 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741445"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741475" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 07:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741475" href="?#comment-741475" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741475" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741475"> <div class="moveup"> <div class="ttypography"><p>Sorry for the issue with editorials. I think there is a timeout issue from Polygon. Since I can't resolve it, I will just rewrite it as a PDF form and upload here.</p></div> </div> </div> <div class="reply info"> <a class="comment-741475 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741475 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741475"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="797067" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/YPK" style="position: relative;"> <img src='https://userpic.codeforces.org/1489397/avatar/bd42de2aca7084dd.jpg'/> </a> <div><a href="/profile/YPK" title="Master YPK" class="rated-user user-orange">YPK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/29/2021 11:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-797067" href="?#comment-797067" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="797067" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="797067" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1489397" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-797067"> <div class="moveup"> <div class="ttypography"><p>Weak test cases for D. Consider the following test case </p> <pre><code>3 1 3 1 2 4 6 4 5 5 7 2 3 </code></pre><p>My accepted solution gives YES but the answer is NO.</p></div> </div> </div> <div class="reply info"> <a class="comment-797067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-797067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-797067"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="891199" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav04" style="position: relative;"> <img src='https://userpic.codeforces.org/2093148/avatar/b05253879beed26d.jpg'/> </a> <div><a href="/profile/abhinav04" title="Specialist abhinav04" class="rated-user user-cyan">abhinav04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/27/2022 11:56">19 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-891199" href="?#comment-891199" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="891199" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="2093148" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-891199"> <div class="moveup"> <div class="ttypography"><p>In case someone needs help with problem B, this might help.</p> <div class="spoiler"><b class="spoiler-title">submission</b><div class="spoiler-content" style="display: none;"><p><a href="https://codeforces.com/contest/1284/submission/147841447">https://codeforces.com/contest/1284/submission/147841447</a></p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-891199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-891199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-891199"> </ul> </div> <br/> <div id="editBox-78289" 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 firstPreview78289 = true; var lastPreviewContent78289 = ''; 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=78289] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=78289] 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-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, 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:27:29</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81288aad58e60057',t:'MTY5NjcwNjg0OS42NzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1284D
1284
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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Наполненный оптимизмом, Хёнука проведет конференцию о том, каким будет этот новый год!</p><p>На конференции будет $$$n$$$ лекций. У Хёнука есть два возможных места $$$a$$$ и $$$b$$$ для проведения лекций. Для каждой из $$$n$$$ лекций докладчик указал два временных интервала $$$[sa_i, ea_i]$$$ ($$$sa_i \le ea_i$$$) и $$$[sb_i, eb_i]$$$ ($$$sb_i \le eb_i$$$). Если конференция расположена в месте $$$a$$$, лекция будет проходить с $$$sa_i$$$ до $$$ea_i$$$, а если конференция будет проходить в месте $$$b$$$, лекция будет проходить с $$$sb_i$$$ до $$$eb_i$$$. Хёнука выберет одно из этих мест, и <span class="tex-font-style-bf">все</span> лекции будут проводиться в этом месте.</p><p>Две лекции пересекаются, если они имеют какой-либо общий момент времени. Формально лекция в интервале $$$[x, y]$$$ перекрывается с лекцией в интервале $$$[u, v]$$$ тогда и только тогда, когда $$$\max(x, u) \le \min(y, v)$$$.</p><p>Участник может <span class="tex-font-style-it">посетить</span> подмножество лекций $$$s$$$, если лекции в $$$s$$$ попарно не перекрываются (то есть никакие две не являются пересекающимися). Обратите внимание, что возможность участия может зависеть от того, выбрал ли Хёнука место $$$a$$$ или место $$$b$$$ для проведения конференции.</p><p>Подмножество лекций $$$s$$$ называется <span class="tex-font-style-it">чувствительным к месту проведения</span>, если для одного из мест участник может посетить $$$s$$$, а для другого места участник не может посетить $$$s$$$.</p><p>Чувствительный к месту проведения набор проблематичен для участника, который заинтересован в посещении лекций в множестве $$$s$$$, потому что участник не может быть уверен, будет ли время лекций перекрываться. Хёнука будет счастлив тогда и только тогда, когда не будет наборов, чувствительных к месту. Определите, будет ли Хёнука счастлив.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 100\,000$$$) — количество лекций на конференции.</p><p>Каждая из следующих $$$n$$$ строк содержит четыре целых числа $$$sa_i$$$, $$$ea_i$$$, $$$sb_i$$$, $$$eb_i$$$ ($$$1 \le sa_i, ea_i, sb_i, eb_i \le 10^9$$$, $$$sa_i \le ea_i, sb_i \le eb_i$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<span class="tex-font-style-tt">YES</span>», если Хёнука будет счастлив. Иначе выведите «<span class="tex-font-style-tt">NO</span>».</p><p>Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 2 3 6 3 4 7 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 3 2 4 4 5 6 7 3 4 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 5 2 9 2 4 5 8 3 6 7 11 7 10 12 16 8 11 13 17 9 12 14 18 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Во втором примере подмножество лекций $$$\{1, 3\}$$$ чувствительное к месту, потому что участник не может посетить место $$$a$$$, но может посетить место $$$b$$$.</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="ba1d1846125161d8e28c0bde03357f3c"/> <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="844107ee75ef6ee8a5d433a0bcfbbda150cb7f74"/> <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='ba1d1846125161d8e28c0bde03357f3c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1284%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='ba1d1846125161d8e28c0bde03357f3c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1284">Hello 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='ba1d1846125161d8e28c0bde03357f3c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1284/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы"> хэши </span> </div> <div class="roundbox borderTopRound 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='ba1d1846125161d8e28c0bde03357f3c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="508365"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ba1d1846125161d8e28c0bde03357f3c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="508365"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72725" title="Hello 2020" target="_blank">Hello 2020 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10228" resourceName="Hello 2020" resourceManual="true" src="//codeforces.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/72804" title="Hello 2020 Editorial" target="_blank">Hello 2020 Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10239" resourceName="Hello 2020 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/1284">Задачи</a></li> <li><a href="/contest/1284/submit">Отослать</a></li> <li><a href="/contest/1284/my">Мои посылки</a></li> <li><a href="/contest/1284/status">Статус</a></li> <li><a href="/contest/1284/hacks">Взломы</a></li> <li><a href="/contest/1284/room/1">Комната</a></li> <li><a href="/contest/1284/standings">Положение</a></li> <li><a href="/contest/1284/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4a79f8a6bc513da2f967d167f42a5ec0c1101b1d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Наполненный оптимизмом, Хёнука проведет конференцию о том, каким будет этот новый год!</p><p>На конференции будет $$$n$$$ лекций. У Хёнука есть два возможных места $$$a$$$ и $$$b$$$ для проведения лекций. Для каждой из $$$n$$$ лекций докладчик указал два временных интервала $$$[sa_i, ea_i]$$$ ($$$sa_i \le ea_i$$$) и $$$[sb_i, eb_i]$$$ ($$$sb_i \le eb_i$$$). Если конференция расположена в месте $$$a$$$, лекция будет проходить с $$$sa_i$$$ до $$$ea_i$$$, а если конференция будет проходить в месте $$$b$$$, лекция будет проходить с $$$sb_i$$$ до $$$eb_i$$$. Хёнука выберет одно из этих мест, и <span class="tex-font-style-bf">все</span> лекции будут проводиться в этом месте.</p><p>Две лекции пересекаются, если они имеют какой-либо общий момент времени. Формально лекция в интервале $$$[x, y]$$$ перекрывается с лекцией в интервале $$$[u, v]$$$ тогда и только тогда, когда $$$\max(x, u) \le \min(y, v)$$$.</p><p>Участник может <span class="tex-font-style-it">посетить</span> подмножество лекций $$$s$$$, если лекции в $$$s$$$ попарно не перекрываются (то есть никакие две не являются пересекающимися). Обратите внимание, что возможность участия может зависеть от того, выбрал ли Хёнука место $$$a$$$ или место $$$b$$$ для проведения конференции.</p><p>Подмножество лекций $$$s$$$ называется <span class="tex-font-style-it">чувствительным к месту проведения</span>, если для одного из мест участник может посетить $$$s$$$, а для другого места участник не может посетить $$$s$$$.</p><p>Чувствительный к месту проведения набор проблематичен для участника, который заинтересован в посещении лекций в множестве $$$s$$$, потому что участник не может быть уверен, будет ли время лекций перекрываться. Хёнука будет счастлив тогда и только тогда, когда не будет наборов, чувствительных к месту. Определите, будет ли Хёнука счастлив.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 100\,000$$$) — количество лекций на конференции.</p><p>Каждая из следующих $$$n$$$ строк содержит четыре целых числа $$$sa_i$$$, $$$ea_i$$$, $$$sb_i$$$, $$$eb_i$$$ ($$$1 \le sa_i, ea_i, sb_i, eb_i \le 10^9$$$, $$$sa_i \le ea_i, sb_i \le eb_i$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<span class="tex-font-style-tt">YES</span>», если Хёнука будет счастлив. Иначе выведите «<span class="tex-font-style-tt">NO</span>».</p><p>Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 2 3 6 3 4 7 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 3 2 4 4 5 6 7 3 4 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 5 2 9 2 4 5 8 3 6 7 11 7 10 12 16 8 11 13 17 9 12 14 18 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Во втором примере подмножество лекций $$$\{1, 3\}$$$ чувствительное к месту, потому что участник не может посетить место $$$a$$$, но может посетить место $$$b$$$.</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:54: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:'812493181e45160a',t:'MTY5NjY2NTI1MC42NzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0425\u044d\u0448\u0438, \u0445\u044d\u0448-\u0442\u0430\u0431\u043b\u0438\u0446\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\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", "\u0445\u044d\u0448\u0438", "*2100"]
https://codeforces.com/blog/entry/72804
<!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="17bb3c0a988bbcfabcfbab3b80b286ce"/> <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="Hello 2020 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>Hello 2020 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='17bb3c0a988bbcfabcfbab3b80b286ce'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F72804">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='17bb3c0a988bbcfabcfbab3b80b286ce'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:37:33</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:37:33</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div><div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='17bb3c0a988bbcfabcfbab3b80b286ce'/> <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/ko_osaga">ko_osaga</a></li> <li class="current selectedLava"><a href="/blog/ko_osaga">Blog</a></li> <li><a href="/teams/with/ko_osaga">Teams</a></li> <li><a href="/submissions/ko_osaga">Submissions</a></li> <li><a href="/groups/with/ko_osaga">Groups</a></li> <li><a href="/contests/with/ko_osaga">Contests</a></li> <li><a href="/contests/writer/ko_osaga">Problemsetting</a></li> <li><a href="/streams/ko_osaga">Streams</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ko_osaga" style="text-decoration:none;color:black !important;">ko_osaga's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="73334"> <div class="title"> <a href="/blog/entry/72804"> <p>Hello 2020 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a>, <a href="/topic/73334/en12">history</a>, <span class="format-humantime" title="Jan/04/2020 18:44">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>Since the Polygon tutorial system is currently broken, I will replace the editorial with PDF format. Sorry for the inconvenience!</p><p><a href="https://www.dropbox.com/s/ysttw748rvx46eb/Hello%202020.pdf?dl=0">Solution PDF</a></p><p>Problem A was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203276">Code</a></p><p>Problem B was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203332">Code</a></p><p>Problem C was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203721">Code</a></p><p>Problem D was authored by <a class="rated-user user-orange" href="/profile/nong" title="Master nong">nong</a>. <a href="https://codeforces.com/contest/1284/submission/68203704">Code</a></p><p>Problem E was authored by <a class="rated-user user-orange" href="/profile/ckw1140" title="Master ckw1140">ckw1140</a>. <a href="https://codeforces.com/contest/1284/submission/68203754">Code</a></p><p>Problem F was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203787">Code</a></p><p>Problem G was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203817">Code</a></p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1284" class="notice" style="text-decoration: none;">Hello 2020</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-38652-73334").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "38652", blogEntryId: "72804", 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-73334"><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'>+191</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-73334"><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/ko_osaga"><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/ko_osaga"> ko_osaga </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="Jan/04/2020 18:44">4 years ago</span> </li> <li> <a href="/blog/entry/72804#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/72804#comments"> 157 </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="78289"> <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 (143)</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="570690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SHZhang" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SHZhang" title="International Grandmaster SHZhang" class="rated-user user-red">SHZhang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570690" href="?#comment-570690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570690" class="CommentVoteFrame" data-commentRating="50" data-commentUserId="1150683" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+50</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570690"> <div class="moveup"> <div class="ttypography"><p>When I open the editorial for problem E, I see the editorial for problem C instead. Can the author fix this, please?</p></div> </div> </div> <div class="reply info"> <a class="comment-570690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570690"> <li> <div class="comment"> <table class="comment-table" commentId="570700" commentParentId="570690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570700" href="?#comment-570700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570700" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570700"> <div class="moveup"> <div class="ttypography"><p>Sorry, it's fixed now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570700"> <li> <div class="comment"> <table class="comment-table" commentId="598782" commentParentId="570700"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jokerwyt" style="position: relative;"> <img src='https://userpic.codeforces.org/555567/avatar/247d0346874bdbdd.jpg'/> </a> <div><a href="/profile/jokerwyt" title="Candidate Master jokerwyt" class="rated-user user-violet">jokerwyt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/07/2020 16:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-598782" href="?#comment-598782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570700" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="598782" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555567" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-598782"> <div class="moveup"> <div class="ttypography"><p>Challenge of problem E is nice, but i have no idea how to solve it. Could you provide the solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-598782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-598782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-598782"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/21August" style="position: relative;"> <img src='https://userpic.codeforces.org/452773/avatar/13e016fa74fb3308.jpg'/> </a> <div><a href="/profile/21August" title="Master 21August" class="rated-user user-orange">21August</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570691" href="?#comment-570691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570691" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="452773" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570691"> <div class="moveup"> <div class="ttypography"><p>You got it wrong for E.</p></div> </div> </div> <div class="reply info"> <a class="comment-570691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570691"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570695" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 18:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570695" href="?#comment-570695" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570695" 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-570695"> <div class="moveup"> <div class="ttypography"><p>Really liked problems B and C :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570695"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570706" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TimonKnigge" style="position: relative;"> <img src='https://userpic.codeforces.org/275246/avatar/debe81b88ed671c2.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/TimonKnigge" title="Master TimonKnigge" class="rated-user user-orange">TimonKnigge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570706" href="?#comment-570706" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570706" class="CommentVoteFrame" data-commentRating="86" data-commentUserId="275246" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+86</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570706"> <div class="moveup"> <div class="ttypography"><p>Problem D is a lot more intuitive if you interpret the input as a collection of rectangles, where you are asked if there is a pair of rectangles that overlaps on one axis but not the other. Then a scanline solution is obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-570706 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570706 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570706"> <li> <div class="comment"> <table class="comment-table" commentId="570804" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Skeef79" style="position: relative;"> <img src='https://userpic.codeforces.org/631759/avatar/3033511aaec49179.jpg'/> </a> <div><a href="/profile/Skeef79" title="Candidate Master Skeef79" class="rated-user user-violet">Skeef79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570804" href="?#comment-570804" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570804"> <div class="moveup"> <div class="ttypography"><p>Can you please give some good resources about scanline? </p></div> </div> </div> <div class="reply info"> <a class="comment-570804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570804"> <li> <div class="comment"> <table class="comment-table" commentId="570996" commentParentId="570804"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rezwan.Arefin01" style="position: relative;"> <img src='https://userpic.codeforces.org/358701/avatar/68ec3668b1ccc552.jpg'/> </a> <div><a href="/profile/Rezwan.Arefin01" title="Candidate Master Rezwan.Arefin01" class="rated-user user-violet">Rezwan.Arefin01</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570996" href="?#comment-570996" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570804" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570996" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="358701" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570996"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.topcoder.com/community/competitive-programming/tutorials/line-sweep-algorithms/">Topcoder Tutorials</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570996 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570996 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570996"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570807" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570807" href="?#comment-570807" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570807" class="CommentVoteFrame" data-commentRating="33" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+33</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570807"> <div class="moveup"> <div class="ttypography"><p>That was the original formulation. I came up with the conference statement to make this problem much natural ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-570807 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570807 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570807"> <li> <div class="comment"> <table class="comment-table" commentId="571201" commentParentId="570807"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ghoshsai5000" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ghoshsai5000" title="Pupil ghoshsai5000" class="rated-user user-green">ghoshsai5000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571201" href="?#comment-571201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570807" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571201" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="543439" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571201"> <div class="moveup"> <div class="ttypography"><p>This was eye-opening ! So, the input format is $$$x_1, x_2, y_1, y_2$$$ and we have to look for $$$2$$$ rectangles such that their $$$x$$$-axes coincide but their $$$y$$$ do not or the other way around. </p><p>First time, we sort by $$$x$$$ and for every new line segment we process, we keep track of all the line segments it inserts with. We will check if the corresponding $$$y$$$ of the line segment fits in the bounds of all the line segments it has intersected so far. </p> <ul> <li>$$$y_1$$$ should not be greater than the smallest $$$y_2$$$ seen so far.</li> <li>$$$y_2$$$ should not be lesser than the greatest $$$y_1$$$ seen so far.</li> </ul><p>If you could include this interpretation in the editorial, it would help in understanding a lot :)</p></div> </div> </div> <div class="reply info"> <a class="comment-571201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571201"> <li> <div class="comment"> <table class="comment-table" commentId="571683" commentParentId="571201"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 19:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571683" href="?#comment-571683" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571683" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571683" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571683"> <div class="moveup"> <div class="ttypography"><p>To be honest, I think it very much depends on what you're comfortable with (Specifically, users who love geometry would love this interpretation). For me, it was easier to visualize the problem in the current format (interval format), whereas it took me a while to grasp the rectangle interpretation. It is interesting to see how the problem can be solved in so similar ways for seemingly different interpretations.</p></div> </div> </div> <div class="reply info"> <a class="comment-571683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571683"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="574189" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sthfaceless" style="position: relative;"> <img src='https://userpic.codeforces.org/1176362/avatar/4480df56f05c4612.jpg'/> </a> <div><a href="/profile/sthfaceless" title="Candidate Master sthfaceless" class="rated-user user-violet">sthfaceless</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/18/2020 20:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-574189" href="?#comment-574189" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="574189" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1176362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-574189"> <div class="moveup"> <div class="ttypography"><p>I used it too :)</p></div> </div> </div> <div class="reply info"> <a class="comment-574189 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-574189 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-574189"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570710" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Radewoosh" style="position: relative;"> <img src='https://userpic.codeforces.org/147752/avatar/a91526f3bd0194e8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570710" href="?#comment-570710" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570710" class="CommentVoteFrame" data-commentRating="76" data-commentUserId="147752" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+76</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570710"> <div class="moveup"> <div class="ttypography"><p>When will we be able to submit?</p></div> </div> </div> <div class="reply info"> <a class="comment-570710 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570710 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570710"> <li> <div class="comment"> <table class="comment-table" commentId="570734" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570734" href="?#comment-570734" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570734" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-38" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570734"> <div class="moveup"> <div class="ttypography"><p>In most contests, submission window opens 2 hours after the contest I guess.</p></div> </div> </div> <div class="reply info"> <a class="comment-570734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570734"> <li> <div class="comment"> <table class="comment-table" commentId="570808" commentParentId="570734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WaterColor2037" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/WaterColor2037" title="Master WaterColor2037" class="rated-user user-orange">WaterColor2037</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570808" href="?#comment-570808" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570808" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="876428" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570808"> <div class="moveup"> <div class="ttypography"><p>Why people downvote this?</p></div> </div> </div> <div class="reply info"> <a class="comment-570808 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570808 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570808"> <li> <div class="comment"> <table class="comment-table" commentId="570811" commentParentId="570808"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:40">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570811" href="?#comment-570811" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570808" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570811" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570811"> <div class="moveup"> <div class="ttypography"><p>Because it isn't true. Usually you can submit a few minutes after system tests are over.</p></div> </div> </div> <div class="reply info"> <a class="comment-570811 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570811 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570811"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570748" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570748" href="?#comment-570748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570748" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570748"> <div class="moveup"> <div class="ttypography"><p>Now submission is open.</p></div> </div> </div> <div class="reply info"> <a class="comment-570748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570748"> <li> <div class="comment"> <table class="comment-table" commentId="570761" commentParentId="570748"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570761" href="?#comment-570761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570748" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570761" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570761"> <div class="moveup"> <div class="ttypography"><p>Exactly 2 hours :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570711" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570711" href="?#comment-570711" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570711" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570711"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/72725?#comment-570663">Randomised sol for D</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570711 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570711 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570711"> <li> <div class="comment"> <table class="comment-table" commentId="570714" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570714" href="?#comment-570714" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570714" class="CommentVoteFrame" data-commentRating="59" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+59</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570714"> <div class="moveup"> <div class="ttypography"><p>There is another randomized approach involving hashes. You may assign random number to each lecture and then calculate for each interval the xor of numbers assigned to intervals it intersects. Now you should check that every lecture has same hashes in first and second places...</p></div> </div> </div> <div class="reply info"> <a class="comment-570714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570714"> <li> <div class="comment"> <table class="comment-table" commentId="570730" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570730" href="?#comment-570730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570730"> <div class="moveup"> <div class="ttypography"><p>how do you calculate the xor of the intersections?</p></div> </div> </div> <div class="reply info"> <a class="comment-570730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570730"> <li> <div class="comment"> <table class="comment-table" commentId="570735" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570735" href="?#comment-570735" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570735" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570735" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570735"> <div class="moveup"> <div class="ttypography"><p>I think, scan-line should work. When the interval $$$[l_i,r_i]$$$ opens, you put $$$h_i$$$ in the position $$$r_i$$$ and when this interval closes you take the xor of all numbers on the $$$[l_i, \infty)$$$.</p><p>It should look like <a href="https://ideone.com/Dypu4W">this</a>, but it gets WA-6 and I'm to sleepy to debug it properly.</p></div> </div> </div> <div class="reply info"> <a class="comment-570735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570735"> <li> <div class="comment"> <table class="comment-table" commentId="570764" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570764" href="?#comment-570764" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570764" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570764"> <div class="moveup"> <div class="ttypography"><p>yeah I did same thing but i get wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570764"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571027" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bhj2001" style="position: relative;"> <img src='https://userpic.codeforces.org/602476/avatar/71790bb4a53d93d3.jpg'/> </a> <div><a href="/profile/Bhj2001" title="Master Bhj2001" class="rated-user user-orange">Bhj2001</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571027" href="?#comment-571027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="602476" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571027"> <div class="moveup"> <div class="ttypography"><p>the WA is not because of hash collision <br /> you missed the case when 2 intervals completely overlap</p></div> </div> </div> <div class="reply info"> <a class="comment-571027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571027"> <li> <div class="comment"> <table class="comment-table" commentId="571059" commentParentId="571027"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571059" href="?#comment-571059" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571027" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571059" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571059"> <div class="moveup"> <div class="ttypography"><p>Not really, I just made a silly typo in my segment tree code... I got it accepted now: <a href="/contest/1284/submission/68205086" title="Submission 68205086 by adamant">68205086</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571059 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571059 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571059"> <li> <div class="comment"> <table class="comment-table" commentId="576198" commentParentId="571059"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anodaram" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anodaram" title="International Master anodaram" class="rated-user user-orange">anodaram</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/29/2020 08:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576198" href="?#comment-576198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571059" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576198" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="1314285" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-576198"> <div class="moveup"> <div class="ttypography"><p>Segment Tree is more popular way than multiset for this problem, I think.</p></div> </div> </div> <div class="reply info"> <a class="comment-576198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576198"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570740" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amnesiac_dusk" style="position: relative;"> <img src='https://userpic.codeforces.org/630995/avatar/5c9b8d77d7e96eff.jpg'/> </a> <div><a href="/profile/amnesiac_dusk" title="Grandmaster amnesiac_dusk" class="rated-user user-red">amnesiac_dusk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570740" href="?#comment-570740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570740" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="630995" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570740"> <div class="moveup"> <div class="ttypography"><p>It can also be treated as hashing all maximal cliques of the interval graph which should be sufficient for checking the equality of the graphs as the graph is chordal. My code for reference <a href="/contest/1284/submission/68181402" title="Submission 68181402 by amnesiac_dusk">68181402</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570740"> <li> <div class="comment"> <table class="comment-table" commentId="571137" commentParentId="570740"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tejas_919" style="position: relative;"> <img src='https://userpic.codeforces.org/875719/avatar/25f822a14baf7fbf.jpg'/> </a> <div><a href="/profile/tejas_919" title="Master tejas_919" class="rated-user user-orange">tejas_919</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571137" href="?#comment-571137" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571137" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571137"> <div class="moveup"> <div class="ttypography"><p>Can you tell me where can I learn this stuff about graphs? It would be really helpful of you.</p></div> </div> </div> <div class="reply info"> <a class="comment-571137 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571137 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571137"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570799" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/staniewzki" style="position: relative;"> <img src='https://userpic.codeforces.org/838116/avatar/307490effa9e1ae7.jpg'/> </a> <div><a href="/profile/staniewzki" title="Grandmaster staniewzki" class="rated-user user-red">staniewzki</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570799" href="?#comment-570799" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570799" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838116" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570799"> <div class="moveup"> <div class="ttypography"><p>You can look at my submission, I kept two segment trees — in one i put the value of the lecture on the beggining of the lecture and in the other on the end. Then, for each lecture i checked for lectures than do not intersect, so lectures that have end before the current beggining and the same for other side. </p></div> </div> </div> <div class="reply info"> <a class="comment-570799 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570799 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570799"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571124" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nizil" style="position: relative;"> <img src='https://userpic.codeforces.org/250190/avatar/d1314e6f3fecc96f.jpg'/> </a> <div><a href="/profile/Nizil" title="Expert Nizil" class="rated-user user-blue">Nizil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571124" href="?#comment-571124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571124" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="250190" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571124"> <div class="moveup"> <div class="ttypography"><p>I have a rather neat code doing this that might help: <a href="/contest/1284/submission/68239280" title="Submission 68239280 by Nizil">68239280</a>. I used the formula:</p> <center>$$$\{\text{Lectures that intersect lecture $$$l$$$}\} = \{\text{Lectures that start before $$$l$$$ ends}\} \setminus \{\text{Lectures that end before $$$l$$$ starts}\}$$$</center><p>. Note that if a lecture ends before $$$l$$$ starts, then it also begins before $$$l$$$ ends so in the subtraction every element of the latter set is contained in the former set. Also note that we do a XOR both when we add and when we remove a set.</p></div> </div> </div> <div class="reply info"> <a class="comment-571124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571124"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570746" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570746" href="?#comment-570746" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570746" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570746" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570746"> <div class="moveup"> <div class="ttypography"><p>My solution uses hashes also :)</p><p>Let's calculate value $$$sumA=\sum_{i \, intersects \, j}(h_i\cdot h_j)$$$ by some modulo for segments in A and the same $$$sumB$$$ for segments in B. Here, $$$h_i$$$ are some random values. This can be calculated with scanline. The answer is &quot;YES&quot; iff $$$sumA=sumB$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570746 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570746 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570746"> <li> <div class="comment"> <table class="comment-table" commentId="570766" commentParentId="570746"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570766" href="?#comment-570766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570746" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570766"> <div class="moveup"> <div class="ttypography"><p>yeah me too but i got wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570766"> <li> <div class="comment"> <table class="comment-table" commentId="570861" commentParentId="570766"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570861" href="?#comment-570861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570766" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570861"> <div class="moveup"> <div class="ttypography"><p>Maybe my code will be helpful: <a href="/contest/1284/submission/68181544" title="Submission 68181544 by VladProg">68181544</a></p><p>It doesn't use any data structures. Only two scan lines.</p></div> </div> </div> <div class="reply info"> <a class="comment-570861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570861"> <li> <div class="comment"> <table class="comment-table" commentId="570871" commentParentId="570861"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570871" href="?#comment-570871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570871"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-570871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570871"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570903" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lemelisk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lemelisk" title="Master lemelisk" class="rated-user user-orange">lemelisk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570903" href="?#comment-570903" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570903" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="513315" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570903"> <div class="moveup"> <div class="ttypography"><p>You can just treat intersections as long number in binary notification (zero means no intersection with given index's segment, one means intersection) and use its remainder as hash. See my submission <a href="https://codeforces.com/contest/1284/submission/68191562">https://codeforces.com/contest/1284/submission/68191562</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570903 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570903 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570903"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571092" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571092" href="?#comment-571092" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571092" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571092"> <div class="moveup"> <div class="ttypography"><p>I just leave it here. I also assign random number to each lecture, and then calculate some hashes. But to avoid cases when one segment completely inside in other, I just took complement approach. I get hash of all segments that doesn't intersect with selected. They are those who ends before selected, or starts after selected. So, I have two BIT for each place: one for lectures ending at time X and one for lectures starting at time X. This is done with packed coordinates and four BIT for each set of random identifiers. <a href="/contest/1284/submission/68198554" title="Submission 68198554 by r57shell">68198554</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571092 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571092 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571092"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570994" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570994" href="?#comment-570994" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570994" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570994"> <div class="moveup"> <div class="ttypography"><p>Me too.</p></div> </div> </div> <div class="reply info"> <a class="comment-570994 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570994 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570994"> <li> <div class="comment"> <table class="comment-table" commentId="570995" commentParentId="570994"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570995" href="?#comment-570995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570994" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570995"> <div class="moveup"> <div class="ttypography"><p>My randomised solution also passed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570995"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570712" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/GyojunYoun" style="position: relative;"> <img src='https://userpic.codeforces.org/227186/avatar/84d3b7d6c6ddb05c.jpg'/> </a> <div><a href="/profile/GyojunYoun" title="Grandmaster GyojunYoun" class="rated-user user-red">GyojunYoun</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570712" href="?#comment-570712" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570712" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570712" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="227186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570712"> <div class="moveup"> <div class="ttypography"><p>Thank you for setting these wonderful problems. Unlike other geometry probs, E is so beautiful that I was impressed :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570712 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570712 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570712"> <li> <div class="comment"> <table class="comment-table" commentId="570805" commentParentId="570712"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mango_lassi" style="position: relative;"> <img src='https://userpic.codeforces.org/519408/avatar/69109d1881b4b829.jpg'/> </a> <div><a href="/profile/mango_lassi" title="International Grandmaster mango_lassi" class="rated-user user-red">mango_lassi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570805" href="?#comment-570805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570712" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-29" data-commentUserId="519408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570805"> <div class="moveup"> <div class="ttypography"><p>Just what part of E do you think is beautiful? I agree that the model solution doesn't seem bad, but that is only in comparison to how painful writing code for the not-totally-magic solutions is. A problem with many easy to find ugly solutions does not turn good from the existence of a beautiful solution that is very difficult to find.</p></div> </div> </div> <div class="reply info"> <a class="comment-570805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570805"> <li> <div class="comment"> <table class="comment-table" commentId="570812" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570812" href="?#comment-570812" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570812" class="CommentVoteFrame" data-commentRating="62" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+62</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570812"> <div class="moveup"> <div class="ttypography"><p>I don't get the point. If you failed to find good solution, then it's our fault?</p></div> </div> </div> <div class="reply info"> <a class="comment-570812 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570812 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570812"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570838" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570838" href="?#comment-570838" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570838" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570838" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570838"> <div class="moveup"> <div class="ttypography"><p>Well, I found it really interesting what you can solve it in $$$O(n^2)$$$. <a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a> is really similar problem and I believe it can only be solved in $$$O(n^3)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570838 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570838 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570838"> <li> <div class="comment"> <table class="comment-table" commentId="570840" commentParentId="570838"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570840" href="?#comment-570840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570838" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570840"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-red" href="/profile/OnionPringles" title="International Grandmaster OnionPringles">OnionPringles</a> told me about the $$$O(n^2\log n)$$$ solution of that problem. Of course, it's much harder than our problem's solution, in any aspect.</p></div> </div> </div> <div class="reply info"> <a class="comment-570840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570840"> <li> <div class="comment"> <table class="comment-table" commentId="570867" commentParentId="570840"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570867" href="?#comment-570867" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570867" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570867"> <div class="moveup"> <div class="ttypography"><p>After I found $$$3x_3+4x_4+5x_5$$$ I thought I need $$$x_5$$$... After 4 TLE attempts, I saw the magic :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570867 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570867 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570867"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570722" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iaNTU" style="position: relative;"> <img src='https://userpic.codeforces.org/568681/avatar/e2c4a458dc77ff9b.jpg'/> </a> <div><a href="/profile/iaNTU" title="International Master iaNTU" class="rated-user user-orange">iaNTU</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570722" href="?#comment-570722" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570722" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-15" data-commentUserId="568681" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570722"> <div class="moveup"> <div class="ttypography"><p>Seems like you don't understand what &quot;right after&quot; means.</p></div> </div> </div> <div class="reply info"> <a class="comment-570722 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570722 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570722"> <li> <div class="comment"> <table class="comment-table" commentId="570728" commentParentId="570722"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570728" href="?#comment-570728" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570722" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570728" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-16" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570728"> <div class="moveup"> <div class="ttypography"><p>Right after systest. I'm sorry for F.</p></div> </div> </div> <div class="reply info"> <a class="comment-570728 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570728 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570728"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570739" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570739" href="?#comment-570739" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570739" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570739"> <div class="moveup"> <div class="ttypography"><p>Does the following flow solution for F run in time?</p><p>Create three sets of nodes A, B, and C. A represents the first set of edges, C represents the second set of edges. We need to match as many nodes in A as we can with nodes in C. Set B represents all the nodes in the tree. Each node in A and C will be connected to the two nodes that the edge it represents in connected to. We then run flow from the nodes in A to the nodes in C.</p><p>This graph has O(n) edges and a max flow of O(n).</p></div> </div> </div> <div class="reply info"> <a class="comment-570739 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570739 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570739"> <li> <div class="comment"> <table class="comment-table" commentId="570749" commentParentId="570739"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570749" href="?#comment-570749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570739" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570749"> <div class="moveup"> <div class="ttypography"><p>Actually, nevermind, this just doesn't work</p></div> </div> </div> <div class="reply info"> <a class="comment-570749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570749"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570743" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/snorkel" style="position: relative;"> <img src='https://userpic.codeforces.org/1360865/avatar/4aa0ab75c5725b5.jpg'/> </a> <div><a href="/profile/snorkel" title="Expert snorkel" class="rated-user user-blue">snorkel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570743" href="?#comment-570743" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360865" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570743"> <div class="moveup"> <div class="ttypography"><p>When the codes will be available?</p></div> </div> </div> <div class="reply info"> <a class="comment-570743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570743"> <li> <div class="comment"> <table class="comment-table" commentId="570767" commentParentId="570743"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570767" href="?#comment-570767" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570743" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570767" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570767"> <div class="moveup"> <div class="ttypography"><p>Code is available now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570767"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570750" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570750" href="?#comment-570750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570750" class="CommentVoteFrame" data-commentRating="12" 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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570750"> <div class="moveup"> <div class="ttypography"><p>For F we can prove that answer always equals $$$n - 1$$$ easily using Hall theorem. Pick any $$$k$$$ edges in first tree, we want to prove that there are at least $$$k$$$ edges in the second tree which can be used to replace at least one of picked edges. Let's remove all picked edges from the tree, then it splits to $$$k + 1$$$ components. For each edge in the second tree let's draw an edge between components containing endpoints of the edge. Since the tree was connected before compressing edges it is still connected now, which means it has at least $$$k$$$ edges which are not self-loops, which means there are at least $$$k$$$ edges which can be used to replace one of picked edges.</p></div> </div> </div> <div class="reply info"> <a class="comment-570750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570750"> <li> <div class="comment"> <table class="comment-table" commentId="570752" commentParentId="570750"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 19:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570752" href="?#comment-570752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570750" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570752" 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-570752"> <div class="moveup"> <div class="ttypography"><p>Sadly this proof gives no clue on how to find the matching</p></div> </div> </div> <div class="reply info"> <a class="comment-570752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570752"> <li> <div class="comment"> <table class="comment-table" commentId="570774" commentParentId="570752"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570774" href="?#comment-570774" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570774" 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-570774"> <div class="moveup"> <div class="ttypography"><p>In my solution (tl;dr <a href="https://codeforces.com/blog/entry/72725?#comment-570604">here</a>), it just turns out while I'm looking for some characteristics of the matching that it is perfect, and the argument for that is kinda similar to Hall's theorem — it also deals with sets of edges in T2 and adjacent edges in T1. It doesn't seem to be particularly useful for finding a way to compute a matching quickly, though.</p></div> </div> </div> <div class="reply info"> <a class="comment-570774 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570774 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570774"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570772" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570772" href="?#comment-570772" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570772" class="CommentVoteFrame" data-commentRating="20" 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;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570772"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p><p>Pick a 1 edge (u, v) from the T1, s.t. u is the leaf in T1. We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A). We can find matching, (u, v) in T1 &amp; (u, w) in T2, and remove those edges. For all x($$$x \neq w$$$), if there is a edge (u, x) in T2, we change u to v. it means, remove (u, x) and add(v, x) (step B). As a result, we can remove vertexes u and reduce problem size by one(after operate, T2 remained as tree).</p><p>How to simulate? Bottleneck is the step B, changing (u, x) to (v, x). Therefore we don't change all edges, but simply remove (u, w) and add dummy edge (u, v). We have to find nearest non-dummy edge in step A, but it's all. We can easily do it by Link-Cut Tree</p></div> </div> </div> <div class="reply info"> <a class="comment-570772 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570772 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570772"> <li> <div class="comment"> <table class="comment-table" commentId="570782" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570782" href="?#comment-570782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570782" 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-570782"> <div class="moveup"> <div class="ttypography"><blockquote><p>We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A).</p> </blockquote><p>Tbh when you have this, there's no need for further tricks or LCT. Just HLD over T1, store not yet taken edges in each path in a set (ordered by depth), DFS over T2 and use HLD to simulate the process for each edge in T2. That's my solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-570782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570782"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570785" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OnionPringles" 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/OnionPringles" title="International Grandmaster OnionPringles" class="rated-user user-red">OnionPringles</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570785" href="?#comment-570785" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570785" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="360543" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570785"> <div class="moveup"> <div class="ttypography"><p>I solved step B by merging u,v in T2 by implementing union-find structure on LCT nodes. When merging u and v, cut all preferred children of u and v so that the children can go through union-find structure when they try to access the unpreferred parent. I think it is easy if you have a pre-written LCT code.</p></div> </div> </div> <div class="reply info"> <a class="comment-570785 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570785 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570785"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570791" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gamegame" style="position: relative;"> <img src='https://userpic.codeforces.org/352372/avatar/8717a5b44702348a.jpg'/> </a> <div><a href="/profile/gamegame" title="Legendary Grandmaster gamegame" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>amegame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570791" href="?#comment-570791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="352372" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570791"> <div class="moveup"> <div class="ttypography"><p>You can do binary lifting and dsu, which is much more easier to code than LCT/HLD</p></div> </div> </div> <div class="reply info"> <a class="comment-570791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570791"> <li> <div class="comment"> <table class="comment-table" commentId="571082" commentParentId="570791"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 12:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571082" href="?#comment-571082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570791" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571082" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571082"> <div class="moveup"> <div class="ttypography"><p>I had the same, but tbh in such contests it would be more preferable to just copy LCT.</p></div> </div> </div> <div class="reply info"> <a class="comment-571082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571082"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570884" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570884" href="?#comment-570884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570884" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570884"> <div class="moveup"> <div class="ttypography"><p>I updated my solution to F. It is my favorite in this problem set. Hope you liked it too!</p></div> </div> </div> <div class="reply info"> <a class="comment-570884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570884"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570783" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570783" href="?#comment-570783" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570783" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+61</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570783"> <div class="moveup"> <div class="ttypography"><p>Here is a more intuitive explanation for E. Sorry if it's mentioned already.</p><p>Fix the point $$$p$$$. Translate everything such that $$$p$$$ coincides with the origin. Sort all the other points counter-clockwise. We shall now find the number of quadruples of points that <em>don't</em> form a polygon containing $$$p$$$.</p><p>Now consider some point $$$s$$$. Consider the half-plane $$$H$$$ of points $$$t$$$ such that the cross product $$$s \wedge t$$$ is positive. For a quadrilateral with $$$s$$$ to contain $$$p$$$, it has to have at least one point from $$$H$$$ and at least one point not from $$$H$$$. Conversely, we will count the number of quadruples $$$(s, t_1, t_2, t_3)$$$ such that $$$t_1, t_2, t_3 \in H$$$. It is just the binomial coefficient $$$|H| \choose 3$$$.</p><p>Now do that for all $$$s$$$ and all corresponding $$$H$$$, in linear time, using the two pointers method.</p><p>With iterating over all $$$p$$$ and sorting, the complexity is $$$O (n^2 \log n)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570783 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570783 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570783"> <li> <div class="comment"> <table class="comment-table" commentId="571005" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLamarca" style="position: relative;"> <img src='https://userpic.codeforces.org/379329/avatar/842836a6a188aadb.jpg'/> </a> <div><a href="/profile/VLamarca" title="Master VLamarca" class="rated-user user-orange">VLamarca</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571005" href="?#comment-571005" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571005" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571005" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="379329" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571005"> <div class="moveup"> <div class="ttypography"><p>This solution works for any size of polygon right? For example if the problem was about triangles instead of quadrilaterals</p><p>thanks for sharing it btw </p></div> </div> </div> <div class="reply info"> <a class="comment-571005 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571005 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571005"> <li> <div class="comment"> <table class="comment-table" commentId="571175" commentParentId="571005"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571175" href="?#comment-571175" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571005" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571175" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571175"> <div class="moveup"> <div class="ttypography"><p>Looks like, yeah, the same argument about all points being in one half-plane would work for pentagons and more.</p><p>Now, if the problem asks for <em>convex</em> polygons, it gets trickier, even with quadrilaterals.</p></div> </div> </div> <div class="reply info"> <a class="comment-571175 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571175 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571175"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571064" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Simurgh" style="position: relative;"> <img src='https://userpic.codeforces.org/1365761/avatar/1d3d3be9bd64e4c9.jpg'/> </a> <div><a href="/profile/Simurgh" title="Expert Simurgh" class="rated-user user-blue">Simurgh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571064" href="?#comment-571064" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571064" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1365761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571064"> <div class="moveup"> <div class="ttypography"><p>Where can I learn more about cross products of vectors and how they can be used in geometry problems?</p></div> </div> </div> <div class="reply info"> <a class="comment-571064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571064"> <li> <div class="comment"> <table class="comment-table" commentId="571178" commentParentId="571064"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571178" href="?#comment-571178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571064" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571178"> <div class="moveup"> <div class="ttypography"><p>Basically, scalar product and cross product are similar in behavior to cosine and sine of angle between vectors, respectively. Their signs behave the same.</p><p>The upside is that, more often than not, we are given coordinates of points as integers (or rationals). And computing scalar and cross products can be done using integers only. So we don't have to resort to floating point and then deal with a whole additional class of errors because of loss of precision.</p><p>As for more general overview, a <a href="https://www.google.com/search?q=scalar+product+and+cross+product+in+computational+geometry">Google search</a> lands some nice articles on the first page.</p></div> </div> </div> <div class="reply info"> <a class="comment-571178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571178"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571093" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 13:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571093" href="?#comment-571093" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571093" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571093" class="CommentVoteFrame" data-commentRating="10" 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: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-571093"> <div class="moveup"> <div class="ttypography"><p>How can I actually easily find the sign of the cross product between two vectors? I got an idea of how to do it with the angle between them, but it seems ugly and probably prone to bugs.</p><p>Edit: I found a way on <a href="https://en.wikipedia.org/wiki/Cross_product#Computational_geometry">Wikipedia</a>, scroll down to the Computation Geometry section.</p></div> </div> </div> <div class="reply info"> <a class="comment-571093 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571093 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571093"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570787" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/undisputedAshu" style="position: relative;"> <img src='https://userpic.codeforces.org/327726/avatar/92b4b2153c6ba4e4.jpg'/> </a> <div><a href="/profile/undisputedAshu" title="Pupil undisputedAshu" class="rated-user user-green">undisputedAshu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570787" href="?#comment-570787" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570787" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="327726" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570787"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain for B</p><p>3</p><p>4 2 0 2 0</p><p>6 9 9 8 8 7 7</p><p>1 6</p><p>how is it 7?</p></div> </div> </div> <div class="reply info"> <a class="comment-570787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570787"> <li> <div class="comment"> <table class="comment-table" commentId="570793" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/djm03178" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/djm03178" title="Master djm03178" class="rated-user user-orange">djm03178</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570793" href="?#comment-570793" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570793" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="687688" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570793"> <div class="moveup"> <div class="ttypography"><p>Let's say a = [2,0,2,0], b = [9,9,8,8,7,7], c = [6], then the answers are: aa, ab, ac, ba, bb, ca, and cb.</p></div> </div> </div> <div class="reply info"> <a class="comment-570793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570793"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570794" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gol_en_05" style="position: relative;"> <img src='https://userpic.codeforces.org/838032/avatar/8167074e5c48a57d.jpg'/> </a> <div><a href="/profile/gol_en_05" title="Specialist gol_en_05" class="rated-user user-cyan">gol_en_05</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570794" href="?#comment-570794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570794" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570794"> <div class="moveup"> <div class="ttypography"><p>since 2 0 2 0 has an ascent.so total pairs are 3. 2 nd sequence does not have an ascent but pairs (2,2),(2,1) has ascent. similarly for 3rd sequence pairs(3,1) and(3,2) has ascent. so total 7 pairs are possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-570794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570794"> <li> <div class="comment"> <table class="comment-table" commentId="570904" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570904" href="?#comment-570904" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570904" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570904"> <div class="moveup"> <div class="ttypography"><p>I'm struggling to understand what does &quot;but pairs (2,2),(2,1) has ascent&quot; mean. Can you please elaborate? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-570904 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570904 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570904"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570916" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570916" href="?#comment-570916" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570916" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570916"> <div class="moveup"> <div class="ttypography"><p>Thanks I got it!</p></div> </div> </div> <div class="reply info"> <a class="comment-570916 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570916 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570916"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570795" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BOGDAN_" 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/BOGDAN_" title="Expert BOGDAN_" class="rated-user user-blue">BOGDAN_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570795" href="?#comment-570795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570795" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="635882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570795"> <div class="moveup"> <div class="ttypography"><p>Let 1, 2, 3 — indexes of arrays. Here is &quot;1 + 2&quot;</p><p>&quot;1 + 3&quot;</p><p>&quot;1 + 1&quot;</p><p>&quot;2 + 2&quot;</p><p>&quot;2 + 1&quot;</p><p>&quot;3 + 1&quot;</p><p>&quot;3 + 2&quot;</p><p>At all — answer 7.</p></div> </div> </div> <div class="reply info"> <a class="comment-570795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570803" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Wa-Automaton" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Wa-Automaton" title="Candidate Master Wa-Automaton" class="rated-user user-violet">Wa-Automaton</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570803" href="?#comment-570803" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570803" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570803" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1365147" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570803"> <div class="moveup"> <div class="ttypography"><p>For D, removing operation is at time ea_i + 1 ?</p><p>UPD: It's fixed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570803 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570803 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570803"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570816" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570816" href="?#comment-570816" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570816" 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="570816" 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-570816"> <div class="moveup"> <div class="ttypography"><p>D can be solved using &quot;Job scheduling &quot; algorithm. Initially we check all the intervals for both the venues individually,whether they overlap,if we get different answer,answer is &quot;NO&quot;.</p><p>If we get same answer and both timings of both venues don't overlap,then answer is &quot;YES&quot;.</p><p>If we get &quot;over-lap&quot; for both,there is a possibility that removing some lectures might make one venue overlapping and other non_overlapping</p><p>eg: 1 2 3 4</p> <pre>3 4 4 5 4 5 6 7</pre><p>In this case,we use job scheduling algorithm to find the largest no of lectures that can be present such that,lecture timings don't overlap for venue A.</p><p>Keep only those lectures for B,check if answer is different for both venues,do the same thing for venue B.</p><p><a href="/contest/1284/submission/68206806" title="Submission 68206806 by AjaySabarish">68206806</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570816 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570816 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570816"> <li> <div class="comment"> <table class="comment-table" commentId="571060" commentParentId="570816"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571060" href="?#comment-571060" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570816" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571060" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571060"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/AjaySabarish" title="Expert AjaySabarish">AjaySabarish</a> Hi, can you please explain the part about &quot;non over-lap&quot; in a little detail?How is there a possibility that removing some lectures might make one venue overlapping and other non_overlapping? I also thought about job scheduling algo but as mentioned in comments, did not consider such cases like finding interval in a and then checking them in b and vice versa. Do they both not give same result? </p></div> </div> </div> <div class="reply info"> <a class="comment-571060 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571060 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571060"> <li> <div class="comment"> <table class="comment-table" commentId="571066" commentParentId="571060"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 11:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571066" href="?#comment-571066" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571060" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571066" 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-571066"> <div class="moveup"> <div class="ttypography"><p>Sry there was a typo,now corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-571066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571066"> <li> <div class="comment"> <table class="comment-table" commentId="571198" commentParentId="571066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571198" href="?#comment-571198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571198"> <div class="moveup"> <div class="ttypography"><p>Still can you explain that point about removing some lectures?</p></div> </div> </div> <div class="reply info"> <a class="comment-571198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571198"> <li> <div class="comment"> <table class="comment-table" commentId="571219" commentParentId="571198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571219" href="?#comment-571219" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571219" 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-571219"> <div class="moveup"> <div class="ttypography"><p>Consider the above example,which I gave </p><p>3</p><p>1 2 3 4</p><p>3 4 4 5</p><p>4 5 6 7</p><p>Now,the timings overlap for both venues,but if you remove lecture 3,timings dont overlap for venue A but overlap for venue B.</p><p>This is the last case which I was talking about,now you have to use job scheduling to find the answer.</p><p>Find the highest number of non overlapping segments for A,it is lecture 1,2.</p><p>Now keep only these lectures for both venues,now the segments for B should also not overlap for &quot;not venue sensitive&quot;. But it is overlapping,so it is venue sensitive</p></div> </div> </div> <div class="reply info"> <a class="comment-571219 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571219 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571219"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570825" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SajidZakaria" style="position: relative;"> <img src='https://userpic.codeforces.org/553136/avatar/f6d8cc00ec65b842.jpg'/> </a> <div><a href="/profile/SajidZakaria" title="Candidate Master SajidZakaria" class="rated-user user-violet">SajidZakaria</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570825" href="?#comment-570825" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570825" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="553136" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570825"> <div class="moveup"> <div class="ttypography"><p>The test cases in D were very &quot;weak&quot;. My solution : <a href="/contest/1284/submission/68205621" title="Submission 68205621 by SajidZakaria">68205621</a></p><p>For very large N, it's enough to only check if each of the lectures have the same number of intersections in A and B. Taking advantage of the fact that it's hard to put up a test case that avoids being fooled that way.</p></div> </div> </div> <div class="reply info"> <a class="comment-570825 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570825 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570825"> <li> <div class="comment"> <table class="comment-table" commentId="634898" commentParentId="570825"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Prajwal_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Prajwal_" title="Expert Prajwal_" class="rated-user user-blue">Prajwal_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/02/2020 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-634898" href="?#comment-634898" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570825" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="634898" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360518" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-634898"> <div class="moveup"> <div class="ttypography"><p>but how will you calculate the intersections in O(n) time.Can you explain once more??</p></div> </div> </div> <div class="reply info"> <a class="comment-634898 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-634898 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-634898"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570829" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570829" href="?#comment-570829" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570829" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570829"> <div class="moveup"> <div class="ttypography"><p>Can you share other solutions to E? Except <a class="rated-user user-orange" href="/profile/Gassa" title="International Master Gassa">Gassa</a>'s (above)</p></div> </div> </div> <div class="reply info"> <a class="comment-570829 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570829 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570829"> <li> <div class="comment"> <table class="comment-table" commentId="570852" commentParentId="570829"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570852" href="?#comment-570852" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570829" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570852" 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="570852" class="CommentVoteFrame" data-commentRating="45" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+45</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570852"> <div class="moveup"> <div class="ttypography"><p>I'll put it short:</p> <ul> <li>(By <a class="rated-user user-red" href="/profile/kdh9949" title="International Grandmaster kdh9949">kdh9949</a> <a class="rated-user user-orange" href="/profile/jihoon" title="International Master jihoon">jihoon</a>) Find $$$f(p)$$$ for each point. You can see that the set can enclose $$$p$$$ iff its convex hull contains $$$p$$$. Checking the containment is hard, so sort by angle, and eliminate the set that does not contain $$$p$$$, which reduces to almost similar sweep with model code. I think this is the easiest solution to come up with.</li> <li>(By <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a>) The answer depends on the 2 * (number of convex quadrilaterals) + (number of concave quadrilaterals). We denote this number $$$A$$$. I think the answer is $$$(A - 2\binom{n}{4}) \times (n-4)/2$$$, or something like that. This problem is bit harder, so you need another type of angular sweep like JOI Open 2017 Bulldozer. I think this is more involved to code, but our great tester <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a> took exactly 12 minutes to AC this.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-570852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570852"> <li> <div class="comment"> <table class="comment-table" commentId="571006" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/NoLongerRed" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/NoLongerRed" title="Grandmaster NoLongerRed" class="rated-user user-red">NoLongerRed</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571006" href="?#comment-571006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571006" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="567645" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571006"> <div class="moveup"> <div class="ttypography"><p>My solution is pretty much the same as molamola's solution and I think it is not necessary to do a cool angular sweep:<br />Let $$$X$$$ be the number of $$$((A,B,C),D)$$$ such that $$$D$$$ lies in $$$ABC$$$ and $$$(A,B,C)$$$ is an unordered tuple. The answer is $$$(n-4)X/2$$$.<br />$$$X$$$ can be counted easily: fixing $$$D$$$ and sort other points by the angles, then do a bunch of lower bound.</p></div> </div> </div> <div class="reply info"> <a class="comment-571006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571006"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571012" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571012" href="?#comment-571012" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571012" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571012"> <div class="moveup"> <div class="ttypography"><p>Thanks for sharing. The solution in Editorial really beautiful, but I don't know. Is that possible to came up with such solution in ~1 hour?</p></div> </div> </div> <div class="reply info"> <a class="comment-571012 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571012 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571012"> <li> <div class="comment"> <table class="comment-table" commentId="571014" commentParentId="571012"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571014" href="?#comment-571014" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571012" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571014" 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="571014" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571014"> <div class="moveup"> <div class="ttypography"><p>Actually my solution submitted during the contest is exactly same as the tutorial solution. In fact, I tried to compute all of $$$x$$$, $$$y$$$, and $$$z$$$, so I double-counted not only the edges of the convex hull but also the diagonal edges, to obtain three linear equations.</p> <center>$$$ x + y + z = {n \choose 5} \\ 5x + 4y + 3z = sth \\ 5x + 6y + 7z = sth $$$</center><p>Unfortunately, this linear system was undetermined, and all I can get was $$$(y + 2z)$$$. That was when I felt quite disappointed. But surprisingly, the answer to the problem happened to be exactly $$$(y + 2z)$$$, so I could finally solve the problem.</p><p>At first, I thought I was lucky enough to find a solution with such unsolvable system. So I headed to this tutorial to read the &quot;official&quot; solution, only to find my solution again. Thanks to your question, I found it in the comments :-)</p><p><a href="/contest/1284/submission/68196878" title="Submission 68196878 by jo_on">68196878</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571014 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571014 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571014"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570830" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570830" href="?#comment-570830" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570830" class="CommentVoteFrame" data-commentRating="3" 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: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-570830"> <div class="moveup"> <div class="ttypography"><p>Just curious,did everyone who solved C in contest,prove the solution?It was not so obvious to me,deciphering and processing what a &quot;framed segment&quot; is,took a lot of time.</p><p>Finding pattern was quite difficult,as manually generating test case even for n=4 is difficult</p><p>Lot of people solved it,is there any other idea?</p></div> </div> </div> <div class="reply info"> <a class="comment-570830 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570830 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570830"> <li> <div class="comment"> <table class="comment-table" commentId="570899" commentParentId="570830"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570899" href="?#comment-570899" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570830" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570899" class="CommentVoteFrame" data-commentRating="2" 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:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570899"> <div class="moveup"> <div class="ttypography"><p>Hi, If you now know what a &quot;framed segment&quot; is, then try to formulate number of &quot;framed segment&quot; of a particular length for a given n. For example: if we want to count &quot;framed segement&quot; of length 1. Let's first consider all &quot;framed segment&quot; containing only digit 1. For this &quot;framed segment&quot; to be at leftmost, there are (n — 1)! permutations. Similar argument goes for its other positions as well. This gives us count : (n — 1)! * n. Now, there are total of n single digits like &quot;1&quot; which can make single length &quot;framed segement&quot;. Thus now count for all single length &quot;framed segement&quot; is : (n — 1)! * n * n (something missing?). I have tried to explain the solution with single length fragment above with some details missing which I think you will figure out. Please try to come-up with a general formulation for any &quot;framed segment&quot;length x for a given n. Summing it all up will give you the answer. Link to my submission : <a href="https://codeforces.com/contest/1284/submission/68187501">Here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570899 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570899 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570899"> <li> <div class="comment"> <table class="comment-table" commentId="570912" commentParentId="570899"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570912" href="?#comment-570912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570899" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570912" 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-570912"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot,I get the solution,but I am just curious about the high number of submissions,was it so obvious?did everyone actually prove it or used their intuition to get it?</p></div> </div> </div> <div class="reply info"> <a class="comment-570912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570912"> <li> <div class="comment"> <table class="comment-table" commentId="570917" commentParentId="570912"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570917" href="?#comment-570917" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570912" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570917" 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-570917"> <div class="moveup"> <div class="ttypography"><p>I guess that depends on one's way of counting up to the answer. And from the number of submissions, it feels like people are actually good at counting..:P</p></div> </div> </div> <div class="reply info"> <a class="comment-570917 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570917 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570917"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kiimak" style="position: relative;"> <img src='https://userpic.codeforces.org/780779/avatar/9d6b81e1dd625cd6.jpg'/> </a> <div><a href="/profile/kiimak" title="Candidate Master kiimak" class="rated-user user-violet">kiimak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570849" href="?#comment-570849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570849" 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="570849" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="780779" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570849"> <div class="moveup"> <div class="ttypography"><p>Hi, I think I found a test case for problem D where my solution gets accepted but it should be incorrect.</p> <pre><code>5 1 10 1 10 2 20 11 30 11 30 2 20 21 40 21 40 31 50 31 50 </code></pre><p>I've checked with the code given in the tutorial, the answer is NO, but my solution gives YES. <a href="/contest/1284/submission/68207409" title="Submission 68207409 by kiimak">68207409</a></p><p>I've modeled it as a graph and put an edge (u, v) if lecture u and v meet. I thought it would be enough to check two things for graph A and B (venue A and B)</p> <ul> <li>the number of degrees for each lecture</li> <li>the lecture set of each component</li> </ul><p>I've submitted it after the contest so it doesn't effect my ratings, but I thought it was worth mentioning.</p></div> </div> </div> <div class="reply info"> <a class="comment-570849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570849"> <li> <div class="comment"> <table class="comment-table" commentId="570891" commentParentId="570849"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ormlis" style="position: relative;"> <img src='https://userpic.codeforces.org/1250517/avatar/5b32008c179f4f98.jpg'/> </a> <div><a href="/profile/Ormlis" title="Legendary Grandmaster Ormlis" class="rated-user user-legendary"><span class="legendary-user-first-letter">O</span>rmlis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570891" href="?#comment-570891" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570891" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1250517" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570891"> <div class="moveup"> <div class="ttypography"><p>I made the same mistake. I tried to find a test case where this is not true, but I could not. Thanks you</p></div> </div> </div> <div class="reply info"> <a class="comment-570891 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570891 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570891"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DJoker99" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/DJoker99" title="Pupil DJoker99" class="rated-user user-green">DJoker99</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570865" href="?#comment-570865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570865" 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="570865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="886083" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570865"> <div class="moveup"> <div class="ttypography"><p>Solution for B [Best :- O(n) Worst :- O(nlogn)]</p><p><a href="https://codeforces.com/contest/1284/submission/68210022">https://codeforces.com/contest/1284/submission/68210022</a></p><p>The condition for a non-ascent sequence a and a non-ascen sequence b to form an ascenting sequence is</p><p><code>min(a) &lt;max(b)</code></p> <ol> <li>First traverse the lists and store max and min in two separate vectors.</li> <li>if a sequence has ascent ie if an element greater than current min or current max occurs then that sequence will always give an ascenting sequence hence do <code>cnt = cnt + 2*n-1</code> <code>n--;</code> because that sequence will form 2n-1 sequences on concatenation</li> <li><p>Sort the max and min vectors then use two pointer approach.</p></li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-570865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570865"> <li> <div class="comment"> <table class="comment-table" commentId="570973" commentParentId="570865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 00:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570973" href="?#comment-570973" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570865" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570973" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570973" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570973"> <div class="moveup"> <div class="ttypography"><p>Involving sort gives already nlogn solution) - <a href="https://codeforces.com/contest/1284/submission/68206308">my code</a> — P. S. I have similar solution, but simpler.</p></div> </div> </div> <div class="reply info"> <a class="comment-570973 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570973 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570973"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570877" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prateek_aries" style="position: relative;"> <img src='https://userpic.codeforces.org/780171/avatar/c6136d0edef16466.jpg'/> </a> <div><a href="/profile/prateek_aries" title="Expert prateek_aries" class="rated-user user-blue">prateek_aries</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570877" href="?#comment-570877" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570877" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="780171" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570877"> <div class="moveup"> <div class="ttypography"><p>Someone please explain me the meaning of the last statement in C. &quot;By observing that there exist exactly n−len+1 pairs with 1≤l≤r≤n,r−l+1=len, we can simply multiply this number for each length, giving a O(n) time solution.&quot; Please give any example.</p></div> </div> </div> <div class="reply info"> <a class="comment-570877 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570877 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570877"> <li> <div class="comment"> <table class="comment-table" commentId="570981" commentParentId="570877"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570981" href="?#comment-570981" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570877" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570981" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570981"> <div class="moveup"> <div class="ttypography"><p>Example of what is it about: </p><p>Consider n of 5 and len of 3</p> <ul> <li><p>1 2 3</p></li> <li><p>2 3 4</p></li> <li><p>3 4 5</p></li> </ul><p>Permutate each of them, and you will get all framed subarrays for n and len of the example. </p></div> </div> </div> <div class="reply info"> <a class="comment-570981 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570981 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570981"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570883" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/im_sanyam" style="position: relative;"> <img src='https://userpic.codeforces.org/605247/avatar/6943d67eaf1d4243.jpg'/> </a> <div><a href="/profile/im_sanyam" title="Expert im_sanyam" class="rated-user user-blue">im_sanyam</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570883" href="?#comment-570883" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570883" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="605247" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570883"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain to me the solution of problem C in a better and intuitive way?</p></div> </div> </div> <div class="reply info"> <a class="comment-570883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570883"> <li> <div class="comment"> <table class="comment-table" commentId="570902" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570902" href="?#comment-570902" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570902" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570902" 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-570902"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570902 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570902 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570902"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570911" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/meiniak" style="position: relative;"> <img src='https://userpic.codeforces.org/803808/avatar/924fee722719da18.jpg'/> </a> <div><a href="/profile/meiniak" title="Newbie meiniak" class="rated-user user-gray">meiniak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570911" href="?#comment-570911" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570911" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="803808" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570911"> <div class="moveup"> <div class="ttypography"><p>let's take n = 5. ar = [1,2,3,4,5] . Now iterate for all possible length of sub-array and count number of good sub-array for that length. k = 1, 2, 3 and so on.</p><p>let take say k = 2 and n = 5. So there are n-k+1 position possible to place k elements i.e If we consider [1,2] then we can place [1,2] in position _ 3 _ 4 _ 5 _ and you can select (n-k+1) elements from n elements to i.e [1,2] , [2,3] , [3,4] and [4,5] . So this is how we got (n-k+1) * (n-k+1) and now we just have to count number of possible permutation of k and (n-k) elements left which is nothing but k! and (n-k)! .** (n-k+1) * (n-k+1) * k! * (n-k)!** is the total answer</p></div> </div> </div> <div class="reply info"> <a class="comment-570911 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570911 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570911"> <li> <div class="comment"> <table class="comment-table" commentId="647624" commentParentId="570911"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lazy_learner" style="position: relative;"> <img src='https://userpic.codeforces.org/926934/avatar/1c97e4ddf06e9813.jpg'/> </a> <div><a href="/profile/lazy_learner" title="Newbie lazy_learner" class="rated-user user-gray">lazy_learner</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2020 08:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-647624" href="?#comment-647624" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570911" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="647624" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926934" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-647624"> <div class="moveup"> <div class="ttypography"><p>But would that not lead to overcounting.<br />Consider the case 3 (1 2) 4 5 and 3 1 2 (4 5).<br />These 2 permutations are same and will be counted twice, once when we consider 1,2 together and second when 4,5 are taken together.</p></div> </div> </div> <div class="reply info"> <a class="comment-647624 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-647624 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-647624"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570914" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rover1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rover1" title="Specialist rover1" class="rated-user user-cyan">rover1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570914" href="?#comment-570914" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570914" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1239447" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570914"> <div class="moveup"> <div class="ttypography"><p>If in question C, we have given a permutation of length n then we need to find happiness... Anyone want to share their approaches ..</p></div> </div> </div> <div class="reply info"> <a class="comment-570914 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570914 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570914"> <li> <div class="comment"> <table class="comment-table" commentId="570918" commentParentId="570914"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570918" href="?#comment-570918" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570914" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570918" 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-570918"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570918"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570927" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/M1v1savva1601" style="position: relative;"> <img src='https://userpic.codeforces.org/539005/avatar/21949389dc808e09.jpg'/> </a> <div><a href="/profile/M1v1savva1601" title="Master M1v1savva1601" class="rated-user user-orange">M1v1savva1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570927" href="?#comment-570927" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570927" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="539005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570927"> <div class="moveup"> <div class="ttypography"><p>Shouldn't it be <strong>eai + 1</strong> in D tutorial?</p></div> </div> </div> <div class="reply info"> <a class="comment-570927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570927"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570941" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AwakeAnay" style="position: relative;"> <img src='https://userpic.codeforces.org/666008/avatar/7043fde46ee0493c.jpg'/> </a> <div><a href="/profile/AwakeAnay" title="Grandmaster AwakeAnay" class="rated-user user-red">AwakeAnay</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 23:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570941" href="?#comment-570941" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="666008" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570941"> <div class="moveup"> <div class="ttypography"><p>I had a overkill solution for $$$D$$$ which led to a good data structures problem. While, others have provided much more elegant solutions, this reduced version is a good problem on its own and worth sharing.</p><p>Here's the problem:</p><p>You are given two sequences $$$a_i$$$ and $$$b_i$$$ of length $$$2N$$$ each. Each number from $$$1$$$ to $$$N$$$ appears exactly twice in both the sequences. You have to solve $$$Q$$$ queries of the following kind:</p><p>Given $$$l$$$, $$$r$$$, $$$x$$$ and $$$y$$$, find the set of distinct elements in $$$(l, r)$$$ in $$$a$$$ is exactly equal to the set of distinct elements in $$$(x, y)$$$ in $$$b$$$. That is, any number $$$u$$$ has an appearance in segment $$$(l, r)$$$ in $$$a$$$ if and only if it has an appearance in segment $$$(x, y)$$$ in $$$b$$$. Try to solve this online in $$$O((N+Q)\log(N))$$$.</p><p>Think of how you can reduce today's $$$D$$$ into this problem.</p><p>My code for today's D: <a href="/contest/1284/submission/68189310" title="Submission 68189310 by AwakeAnay">68189310</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570941"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570975" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/madhav_1999" style="position: relative;"> <img src='https://userpic.codeforces.org/594602/avatar/cad96e04d2a42e66.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/madhav_1999" title="Master madhav_1999" class="rated-user user-orange">madhav_1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570975" href="?#comment-570975" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570975" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="594602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570975"> <div class="moveup"> <div class="ttypography"><p>In D: &quot;Event removing interval [sbi, ebi] from S at time ebi+1.&quot;</p><p><a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a>, I think you made an error here, it should be eai + 1 instead</p></div> </div> </div> <div class="reply info"> <a class="comment-570975 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570975 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570975"> <li> <div class="comment"> <table class="comment-table" commentId="571032" commentParentId="570975"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571032" href="?#comment-571032" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570975" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571032" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571032"> <div class="moveup"> <div class="ttypography"><p>Sorry, fixed. </p></div> </div> </div> <div class="reply info"> <a class="comment-571032 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571032 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571032"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570982" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 02:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570982" href="?#comment-570982" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570982" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570982"> <div class="moveup"> <div class="ttypography"><p>Problem B can also be solved in $$$O(n)$$$. Be $$$asc$$$ the number of sequences that have an ascent. For each sequence, check if it's non-increasing. If it isn't any concatenation we do will have an ascent, so we can add $$$n$$$ to our answer and $$$1$$$ to $$$asc$$$. Now be $$$s$$$ a non-increasing sequence and let's set it as the right part of the concatenation. We will only have an ascent in the concatenation if the left part already has an ascent or has an element smaller than any element in $$$s$$$, specially it's maximum. We have $$$asc$$$ sequences of the first type, so that's easy, and for the second part we can precalculate it by creating an array $$$minfreq$$$ where we store the minimum of each non-increasing sequence in it's position (as $$$s_{i,j} &lt; 10^6$$$) and do a sweep from $$$1$$$ to $$$10^6$$$ to accumulate our sum ($$$minfreq[i] = minfreq[i-1] +minfreq[i]$$$). Now we have our answer for the second part in position $$$minfreq[max(s)-1]$$$, and we can just add both parts to our answer. Since we can precalculate $$$minfreq$$$, $$$max(s)$$$ and $$$asc$$$ in $$$O(n)$$$ and the answer can be calculated in $$$O(1)$$$ using our precalculations total complexity is $$$O(n)$$$ </p></div> </div> </div> <div class="reply info"> <a class="comment-570982 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570982 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570982"> <li> <div class="comment"> <table class="comment-table" commentId="570987" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dblark" style="position: relative;"> <img src='https://userpic.codeforces.org/693276/avatar/70323ef41e4c9add.jpg'/> </a> <div><a href="/profile/dblark" title="International Master dblark" class="rated-user user-orange">dblark</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 03:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570987" href="?#comment-570987" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570987" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="693276" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570987"> <div class="moveup"> <div class="ttypography"><p>Yeah, the same idea with you!</p></div> </div> </div> <div class="reply info"> <a class="comment-570987 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570987 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570987"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571037" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 08:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571037" href="?#comment-571037" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571037" class="CommentVoteFrame" data-commentRating="0" 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:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571037"> <div class="moveup"> <div class="ttypography"><p>I did the same, but this is not O(N). The time Complexity will be O(n + maxELE) where maxELE is the largest sequence element seen in input.</p><p>We were lucky that the constraint on that wasn't 10^9.</p><p>Also consider cases in which n = 5 but the elements are still very large, our code would still take lot of time to execute.</p></div> </div> </div> <div class="reply info"> <a class="comment-571037 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571037 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571037"> <li> <div class="comment"> <table class="comment-table" commentId="571654" commentParentId="571037"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 18:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571654" href="?#comment-571654" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571037" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571654" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571654"> <div class="moveup"> <div class="ttypography"><p>Yeah that's true, the editorial's solution is more general for that same reason</p></div> </div> </div> <div class="reply info"> <a class="comment-571654 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571654 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571654"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571551" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571551" href="?#comment-571551" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571551" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571551"> <div class="moveup"> <div class="ttypography"><p>I cant understand the minfreq[i]=minfreq[i−1]+minfreq[i] . can you explain me </p></div> </div> </div> <div class="reply info"> <a class="comment-571551 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571551 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571551"> <li> <div class="comment"> <table class="comment-table" commentId="571653" commentParentId="571551"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571653" href="?#comment-571653" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571551" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571653" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571653"> <div class="moveup"> <div class="ttypography"><p>It's called accumulated sum. Basically we want minfreq[i] to be the frequency of all numbers $$$\leq$$$ to i, so we need to push our previous array position to our current one, so that we also take into account the occurences of numbers &lt; i, and not just equal to i</p></div> </div> </div> <div class="reply info"> <a class="comment-571653 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571653 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571653"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571001" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Aguin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Aguin" title="Candidate Master Aguin" class="rated-user user-violet">Aguin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571001" href="?#comment-571001" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571001" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="297931" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571001"> <div class="moveup"> <div class="ttypography"><p>How to count different quadrilaterals in problem E?</p></div> </div> </div> <div class="reply info"> <a class="comment-571001 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571001 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571001"> <li> <div class="comment"> <table class="comment-table" commentId="571004" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571004" href="?#comment-571004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571004"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571004"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571007" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 05:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571007" href="?#comment-571007" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571007" class="CommentVoteFrame" data-commentRating="3" 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;">+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-571007"> <div class="moveup"> <div class="ttypography"><p>For example, for each pair of points $$$(i, j)$$$, we can find the number of points on one side of the line i-j ($$$a$$$), the number of points on the other side ($$$N-2-a$$$), sum that up, divide by 2 and subtract $$$2{N\choose 4}$$$. Why? For each 4-tuple of points, if one of them is inside the triangle formed by the other 3 (their convex hull is a triangle), we get 3 lines (inner point, some other point) that are counted here, and when their convex hull is a quadrilateral, we get 2 such lines — its diagonals; we subtract (2 * number of 4-tuples) to get the number of 4-tuples where one point is inside.</p><p>How to find these $$$a$$$ for each pair $$$(i, j)$$$ fast? Let's say that $$$i$$$ is fixed, sort all remaining points by their angle around point $$$i$$$, then consider a line that crosses $$$i$$$, start rotating it and whenever it crosses one of these points, update the current value of $$$a$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-571007 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571007 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571007"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571011" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571011" href="?#comment-571011" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571011" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571011"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> (<a href="/topic/73334/en9">previous revision</a>, <a href="/topic/73334/en10">new revision</a>, <a href="/topic/73334/diff/en9/en10">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-571011 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571011 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571011"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hd7" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Hd7" title="Specialist Hd7" class="rated-user user-cyan">Hd7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571018" href="?#comment-571018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571018" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="559666" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571018"> <div class="moveup"> <div class="ttypography"><p>Could anyone give me a more elaborated explanation for problem D, I didn't grasp the editorial at all.</p></div> </div> </div> <div class="reply info"> <a class="comment-571018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571031" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571031" href="?#comment-571031" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571031" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571031"> <div class="moveup"> <div class="ttypography"><p>Expected a matroid problem, as <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> took matroid class last semester XD</p></div> </div> </div> <div class="reply info"> <a class="comment-571031 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571031 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571031"> <li> <div class="comment"> <table class="comment-table" commentId="571033" commentParentId="571031"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571033" href="?#comment-571033" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571031" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571033" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571033"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/team/65651">matroid fan club!</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571033 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571033 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571033"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571040" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PouyaNavid" style="position: relative;"> <img src='https://userpic.codeforces.org/670316/avatar/c42e949ea38011da.jpg'/> </a> <div><a href="/profile/PouyaNavid" title="Master PouyaNavid" class="rated-user user-orange">PouyaNavid</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 09:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571040" href="?#comment-571040" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571040" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="670316" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571040"> <div class="moveup"> <div class="ttypography"><p>Hack Test for D <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a></p><p>4 1 10 51 60 2 20 44 52 3 40 43 45 42 45 50 50</p></div> </div> </div> <div class="reply info"> <a class="comment-571040 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571040 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571040"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571088" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hazyknight" style="position: relative;"> <img src='https://userpic.codeforces.org/537474/avatar/e2c88ee4c2562699.jpg'/> </a> <div><a href="/profile/Hazyknight" title="International Grandmaster Hazyknight" class="rated-user user-red">Hazyknight</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571088" href="?#comment-571088" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571088" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571088" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="537474" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571088"> <div class="moveup"> <div class="ttypography"><p>Actually, Problem G can be solved easily by matroid intersection. Consider two matroid M1(S,I),M2(S,I), S is the set of wall, M1 is a graph matroid , M2 is a matroid which any black cell has at least to side without wall. Code: <a href="https://codeforces.com/contest/1284/submission/68215804">https://codeforces.com/contest/1284/submission/68215804</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571088 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571088 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571088"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571128" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amstan" style="position: relative;"> <img src='https://userpic.codeforces.org/734003/avatar/344c500da9a98a7f.jpg'/> </a> <div><a href="/profile/amstan" title="Expert amstan" class="rated-user user-blue">amstan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571128" href="?#comment-571128" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571128" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="734003" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571128"> <div class="moveup"> <div class="ttypography"><p>Is there anyone who solved D using coordinate compression and prefix sum ? If so, could you please share your submission.</p></div> </div> </div> <div class="reply info"> <a class="comment-571128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571128"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571138" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HaoxuanXIE" style="position: relative;"> <img src='https://userpic.codeforces.org/1234114/avatar/fa4b56dfead7992e.jpg'/> </a> <div><a href="/profile/HaoxuanXIE" title="Expert HaoxuanXIE" class="rated-user user-blue">HaoxuanXIE</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571138" href="?#comment-571138" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571138" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1234114" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571138"> <div class="moveup"> <div class="ttypography"><p>Why does D need to check in two directions? If I check in one direction, I get wrong answer at 9th point. But I think it is appropriate to check in only one direction.</p></div> </div> </div> <div class="reply info"> <a class="comment-571138 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571138 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571138"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571145" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheeLooser" style="position: relative;"> <img src='https://userpic.codeforces.org/448032/avatar/d5dcfa8c5dbd255f.jpg'/> </a> <div><a href="/profile/TheeLooser" title="Expert TheeLooser" class="rated-user user-blue">TheeLooser</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571145" href="?#comment-571145" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571145" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="448032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571145"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> may as well check how many visits were made to <a href="https://codeforces.com/problemset/problem/1146/H">this</a> page and later to <a href="https://codeforces.com/blog/entry/66639">this</a> page in contest time</p></div> </div> </div> <div class="reply info"> <a class="comment-571145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571145"> <li> <div class="comment"> <table class="comment-table" commentId="571459" commentParentId="571145"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 22:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571459" href="?#comment-571459" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571145" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571459" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571459"> <div class="moveup"> <div class="ttypography"><p>How does that problem help?</p></div> </div> </div> <div class="reply info"> <a class="comment-571459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571459"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571509" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Petr" style="position: relative;"> <img src='https://userpic.codeforces.org/664/avatar/a113c1791cdcd2e1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Petr" title="Legendary Grandmaster Petr" class="rated-user user-legendary"><span class="legendary-user-first-letter">P</span>etr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 01:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571509" href="?#comment-571509" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571509" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="664" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571509"> <div class="moveup"> <div class="ttypography"><p>Re: &quot;Hopefully, the first 80 tests were good enough for the contest.&quot;</p><p>My <a href="https://codeforces.com/contest/1284/submission/68208450">random solution</a> fails on test 87 :) Great job making the tests indeed!</p></div> </div> </div> <div class="reply info"> <a class="comment-571509 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571509 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571509"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571522" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MubtasimShahriar" style="position: relative;"> <img src='https://userpic.codeforces.org/756984/avatar/9113baa4abf04299.jpg'/> </a> <div><a href="/profile/MubtasimShahriar" title="Pupil MubtasimShahriar" class="rated-user user-green">MubtasimShahriar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 05:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571522" href="?#comment-571522" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571522" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756984" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571522"> <div class="moveup"> <div class="ttypography"><p>In Problem D, why does this solution not work? My Solutions is this.</p><p>Sort lectures according to their start-ending time in both venue, Then decide every lecture if it intersects with others in their own venue.</p><p>If there is at least one lecture that make difference in intersecting in both venue, then Subset can not be made. So the answer is no. If every problem either intersects in both venue or does not intersect in both venue then answer is yes. Here is my implementation <a href="/contest/1284/submission/68294866" title="Submission 68294866 by MubtasimShahriar">68294866</a></p><p>Please someone enlighten me where I am misunderstanding.</p></div> </div> </div> <div class="reply info"> <a class="comment-571522 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571522 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571522"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571546" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SLIMSHADYNICK" style="position: relative;"> <img src='https://userpic.codeforces.org/598862/avatar/7629f1b29f0fe807.jpg'/> </a> <div><a href="/profile/SLIMSHADYNICK" title="Candidate Master SLIMSHADYNICK" class="rated-user user-violet">SLIMSHADYNICK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571546" href="?#comment-571546" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571546" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-13" data-commentUserId="598862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-571546"> <div class="moveup"> <div class="ttypography"><p>In problem D, I got wrong answer on test case 14. Can somebody please help.</p></div> </div> </div> <div class="reply info"> <a class="comment-571546 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571546 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571546"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572491" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ftiasch" style="position: relative;"> <img src='https://userpic.codeforces.org/506/avatar/c52be21fbeb4a450.jpg'/> </a> <div><a href="/profile/ftiasch" title="International Grandmaster ftiasch" class="rated-user user-red">ftiasch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/11/2020 00:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572491" href="?#comment-572491" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572491" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="506" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-572491"> <div class="moveup"> <div class="ttypography"><p>2020 begins with two matroid problems. XD</p><p>btw, Challenge in Problem F is called Strong Basis Exchange as in <a href="https://math.mit.edu/~goemans/18438F09/lec11.pdf">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-572491 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572491 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572491"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572780" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Akash79" style="position: relative;"> <img src='https://userpic.codeforces.org/776725/avatar/700a28ac96121584.jpg'/> </a> <div><a href="/profile/Akash79" title="Expert Akash79" class="rated-user user-blue">Akash79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 16:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572780" href="?#comment-572780" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572780" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="776725" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572780"> <div class="moveup"> <div class="ttypography"><p>I am not able to understand problem B's solution.. can anyone please help me out..??</p></div> </div> </div> <div class="reply info"> <a class="comment-572780 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572780 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572780"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 17:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572849" href="?#comment-572849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="572849" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="572849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572849"> <div class="moveup"> <div class="ttypography"><p>Why don't we have to consider the case when there's some period intersecting in A and not intersecting in B? Doesn't that mean that sometimes our code will say 'YES' but the answer is 'NO'. Why? <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a>. EDIT: Ok, I just didn't notice the part of the code where he does the same thing but reversed.</p></div> </div> </div> <div class="reply info"> <a class="comment-572849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572849"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572863" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 18:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572863" href="?#comment-572863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572863" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572863"> <div class="moveup"> <div class="ttypography"><p>What is the hash approach for the problem D?</p></div> </div> </div> <div class="reply info"> <a class="comment-572863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572863"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="576477" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anaksoleh" style="position: relative;"> <img src='https://userpic.codeforces.org/1170460/avatar/27d790d7abbbd3d9.jpg'/> </a> <div><a href="/profile/anaksoleh" title="Newbie anaksoleh" class="rated-user user-gray">anaksoleh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/30/2020 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576477" href="?#comment-576477" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576477" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170460" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-576477"> <div class="moveup"> <div class="ttypography"><p>there is a proof for C solution ?</p></div> </div> </div> <div class="reply info"> <a class="comment-576477 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576477 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576477"> <li> <div class="comment"> <table class="comment-table" commentId="673042" commentParentId="576477"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/XORring-Samurai" style="position: relative;"> <img src='https://userpic.codeforces.org/1384228/avatar/d0258d5ed6604923.jpg'/> </a> <div><a href="/profile/XORring-Samurai" title="Candidate Master XORring-Samurai" class="rated-user user-violet">XORring-Samurai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/02/2020 09:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-673042" href="?#comment-673042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-576477" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="673042" 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="673042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1384228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-673042"> <div class="moveup"> <div class="ttypography"><p>Here is something, that I could think of.</p><p>For each permutation, we have the same $$$r-l$$$. This value varies from $$$0$$$ to $$$n-1$$$ for all $$$n$$$. Now let us consider $$$r-l=d$$$, as a general case. </p><p>For each $$$n$$$, we have $$$n-d$$$ pairs of $$$[l, r]$$$, where $$$r-l=d$$$. Also for all numbers from $$$1$$$ to $$$n$$$, we have $$$n-d$$$ pairs of type $$$[i, j]$$$ such that $$$j-i=d$$$. </p><p>For a segment to be framed, all the other places for each $$$[l, r]$$$ must be occupied by each integer from $$$[i, j]$$$. Therefore, we have $$$d+1$$$ numbers to be arranged in this interval $$$[l, r]$$$ and $$$n-d-1$$$ to be arranged in $$$[1, l-1]$$$ and $$$[r+1, n]$$$. This can be done in $$$(d+1)! * (n-d-1)!$$$ ways. </p><p>But we have $$$n-d$$$ pairs of $$$[l, r]$$$ and $$$n-d$$$ pairs of $$$[i, j]$$$, each of which can occupy this segment. Therefore the answer becomes summation over all $$$d$$$ from $$$0$$$ to $$$n-1$$$: $$$ans = ans + (n-d) * (n-d) * (d+1)! * (n-d-1)!$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-673042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-673042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-673042"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606852" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ThakurSaab" style="position: relative;"> <img src='https://userpic.codeforces.org/1267713/avatar/7c6c4d7b58cddb96.jpg'/> </a> <div><a href="/profile/ThakurSaab" title="Expert ThakurSaab" class="rated-user user-blue">ThakurSaab</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 17:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606852" href="?#comment-606852" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606852" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1267713" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606852"> <div class="moveup"> <div class="ttypography"><p>In problem C , do we consider that the numbers inside a particular segment [l,r] could be different such that, max-min = r-l</p></div> </div> </div> <div class="reply info"> <a class="comment-606852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606852"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="689589" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 07:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689589" href="?#comment-689589" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689589" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689589"> <div class="moveup"> <div class="ttypography"><p>In Problem D I added elements in the segment tree in the decreasing order of eai and then I queried for the previous range if the min of the ls and the maxr intersect with the particular index of a I am addding . I am getting a WA at Test Case 7 for this submission.</p><p>This is my submission link: <a href="https://codeforces.com/contest/1284/submission/91535000">https://codeforces.com/contest/1284/submission/91535000</a></p><p>Can somebody help me with this solution where I went wrong? </p><p>Or is there anyway I can look at the whole testcase then please reply here about how can I do that?</p></div> </div> </div> <div class="reply info"> <a class="comment-689589 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689589 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689589"> <li> <div class="comment"> <table class="comment-table" commentId="689595" commentParentId="689589"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 08:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689595" href="?#comment-689595" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-689589" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689595" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689595"> <div class="moveup"> <div class="ttypography"><p>Never Mind I made a silly typo in the cmp2 function.</p></div> </div> </div> <div class="reply info"> <a class="comment-689595 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689595 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689595"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="722358" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tanishq_code_c" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tanishq_code_c" title="Expert tanishq_code_c" class="rated-user user-blue">tanishq_code_c</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/17/2020 17:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-722358" href="?#comment-722358" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="722358" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1484322" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-722358"> <div class="moveup"> <div class="ttypography"><p>Hi, I am not able to understand the editorial for problem C. can anyone break it down in easy way please ? </p></div> </div> </div> <div class="reply info"> <a class="comment-722358 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-722358 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-722358"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="736312" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheOneYouWant" style="position: relative;"> <img src='https://userpic.codeforces.org/628619/avatar/c785428bde285c3.jpg'/> </a> <div><a href="/profile/TheOneYouWant" title="Master TheOneYouWant" class="rated-user user-orange">TheOneYouWant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/23/2020 05:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-736312" href="?#comment-736312" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="736312" class="CommentVoteFrame" data-commentRating="91" data-commentUserId="628619" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+91</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-736312"> <div class="moveup"> <div class="ttypography"><p>Hello, this seems to be broken (perhaps a sign of how the year 2020 has been so far)</p></div> </div> </div> <div class="reply info"> <a class="comment-736312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-736312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-736312"> <li> <div class="comment"> <table class="comment-table" commentId="737407" commentParentId="736312"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/27/2020 09:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-737407" href="?#comment-737407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-736312" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="737407" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-737407"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> please take a look, thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-737407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-737407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-737407"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741444" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/butterflies" style="position: relative;"> <img src='https://userpic.codeforces.org/1651561/avatar/33dfc9c16e5795ad.jpg'/> </a> <div><a href="/profile/butterflies" title="Specialist butterflies" class="rated-user user-cyan">butterflies</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741444" href="?#comment-741444" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="741444" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="741444" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1651561" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741444"> <div class="moveup"> <div class="ttypography"><p>This question relates to <a href="https://codeforces.com/contest/1284/problem/B">problem B</a>. I have a question with the second example input. Here is the input:</p> <pre><code>3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 </code></pre><p>I believe all arrays have an ascent. In the first array, the pair $$$(i, j) = (3, 4)$$$ works. ($$$a_3 = 0, a_4 = 2.$$$) In the second array, the pair $$$(i, j) = (1, 2)$$$ works. ($$$a_1 = 6, a_2 = 9.$$$) In the third array, the pair $$$(i,j) = (1, 2)$$$ works. ($$$a_1 = 1, a_2 = 6.$$$)</p><p>Thus, shouldn't all pairs of arrays in this case work? There are $$$9$$$ such pairs, but the answer to this should be $$$7.$$$ What is wrong with my reasoning here?</p></div> </div> </div> <div class="reply info"> <a class="comment-741444 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741444 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741444"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741445" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/beetroot" style="position: relative;"> <img src='https://userpic.codeforces.org/1503072/avatar/6668dbf5be4e4495.jpg'/> </a> <div><a href="/profile/beetroot" title="Expert beetroot" class="rated-user user-blue">beetroot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741445" href="?#comment-741445" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741445" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1503072" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741445"> <div class="moveup"> <div class="ttypography"><p>Editorials that didn't age well...</p></div> </div> </div> <div class="reply info"> <a class="comment-741445 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741445 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741445"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741475" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 07:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741475" href="?#comment-741475" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741475" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741475"> <div class="moveup"> <div class="ttypography"><p>Sorry for the issue with editorials. I think there is a timeout issue from Polygon. Since I can't resolve it, I will just rewrite it as a PDF form and upload here.</p></div> </div> </div> <div class="reply info"> <a class="comment-741475 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741475 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741475"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="797067" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/YPK" style="position: relative;"> <img src='https://userpic.codeforces.org/1489397/avatar/bd42de2aca7084dd.jpg'/> </a> <div><a href="/profile/YPK" title="Master YPK" class="rated-user user-orange">YPK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/29/2021 11:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-797067" href="?#comment-797067" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="797067" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="797067" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1489397" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-797067"> <div class="moveup"> <div class="ttypography"><p>Weak test cases for D. Consider the following test case </p> <pre><code>3 1 3 1 2 4 6 4 5 5 7 2 3 </code></pre><p>My accepted solution gives YES but the answer is NO.</p></div> </div> </div> <div class="reply info"> <a class="comment-797067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-797067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-797067"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="891199" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav04" style="position: relative;"> <img src='https://userpic.codeforces.org/2093148/avatar/b05253879beed26d.jpg'/> </a> <div><a href="/profile/abhinav04" title="Specialist abhinav04" class="rated-user user-cyan">abhinav04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/27/2022 11:56">19 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-891199" href="?#comment-891199" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="891199" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="2093148" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-891199"> <div class="moveup"> <div class="ttypography"><p>In case someone needs help with problem B, this might help.</p> <div class="spoiler"><b class="spoiler-title">submission</b><div class="spoiler-content" style="display: none;"><p><a href="https://codeforces.com/contest/1284/submission/147841447">https://codeforces.com/contest/1284/submission/147841447</a></p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-891199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-891199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-891199"> </ul> </div> <br/> <div id="editBox-78289" 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 firstPreview78289 = true; var lastPreviewContent78289 = ''; 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=78289] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=78289] 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-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, 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:27:29</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81288aad58e60057',t:'MTY5NjcwNjg0OS42NzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1284E
1284
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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Любимая видеоигра Кивона теперь проводит новогоднее мероприятие, чтобы мотивировать пользователей! Игра о строительстве и защите замка, поэтому Кивон задумался над следующей загадкой.</p><p>В двумерной плоскости у вас есть набор $$$s = \{(x_1, y_1), (x_2, y_2), \ldots, (x_n, y_n)\}$$$, состоящий из $$$n$$$ различных точек. В множестве $$$s$$$ <span class="tex-font-style-bf">нет трех точек на одной прямой</span>. Мы можем защитить точку $$$p \in s$$$, построив замок. <span class="tex-font-style-bf">Замок</span> — это простой четырехугольник (многоугольник с $$$4$$$ вершинами), который строго покрывает точку $$$p$$$ (то есть точка $$$p$$$ строго внутри четырёхугольника).</p><p>Кивона интересует количество подмножеств $$$s$$$ из $$$4$$$-х точек, которые можно использовать для построения замка, защищающего точку $$$p$$$. Обратите внимание, что если одно подмножество может быть соединено более чем одним способом, чтобы покрыть точку, то оно считается только один раз.</p><p>Пусть $$$f(p)$$$ будет количеством подмножеств из $$$4$$$-х точек, которые могут покрыть точку $$$p$$$. Пожалуйста, посчитайте сумму $$$f(p)$$$ по всем точкам $$$p \in s$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$5 \le n \le 2\,500$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$-10^9 \le x_i, y_i \le 10^9$$$), которые обозначают координаты точки.</p><p>Гарантируется, что все точки различны и что нет трех коллинеарных точек.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму $$$f(p)$$$ по всем точкам $$$p \in 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 -1 0 1 0 -10 -1 10 -1 0 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 0 1 1 2 2 2 1 3 0 -1 -1 -2 -2 -2 -1 -3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 40</pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 588634631 265299215 -257682751 342279997 527377039 82412729 145077145 702473706 276067232 912883502 822614418 -514698233 280281434 -41461635 65985059 -827653144 188538640 592896147 -857422304 -529223472 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 213</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="eab992e3022248e278fbea83b640ea63"/> <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="844107ee75ef6ee8a5d433a0bcfbbda150cb7f74"/> <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='eab992e3022248e278fbea83b640ea63'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1284%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='eab992e3022248e278fbea83b640ea63'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1284">Hello 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='eab992e3022248e278fbea83b640ea63'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1284/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Геометрия"> геометрия </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='eab992e3022248e278fbea83b640ea63'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="508366"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='eab992e3022248e278fbea83b640ea63'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="508366"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72725" title="Hello 2020" target="_blank">Hello 2020 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10228" resourceName="Hello 2020" resourceManual="true" src="//codeforces.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/72804" title="Hello 2020 Editorial" target="_blank">Hello 2020 Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10239" resourceName="Hello 2020 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/1284">Задачи</a></li> <li><a href="/contest/1284/submit">Отослать</a></li> <li><a href="/contest/1284/my">Мои посылки</a></li> <li><a href="/contest/1284/status">Статус</a></li> <li><a href="/contest/1284/hacks">Взломы</a></li> <li><a href="/contest/1284/room/1">Комната</a></li> <li><a href="/contest/1284/standings">Положение</a></li> <li><a href="/contest/1284/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b6bf04d0ed1884db20319a23fb6984c34ad8ceae"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Любимая видеоигра Кивона теперь проводит новогоднее мероприятие, чтобы мотивировать пользователей! Игра о строительстве и защите замка, поэтому Кивон задумался над следующей загадкой.</p><p>В двумерной плоскости у вас есть набор $$$s = \{(x_1, y_1), (x_2, y_2), \ldots, (x_n, y_n)\}$$$, состоящий из $$$n$$$ различных точек. В множестве $$$s$$$ <span class="tex-font-style-bf">нет трех точек на одной прямой</span>. Мы можем защитить точку $$$p \in s$$$, построив замок. <span class="tex-font-style-bf">Замок</span> — это простой четырехугольник (многоугольник с $$$4$$$ вершинами), который строго покрывает точку $$$p$$$ (то есть точка $$$p$$$ строго внутри четырёхугольника).</p><p>Кивона интересует количество подмножеств $$$s$$$ из $$$4$$$-х точек, которые можно использовать для построения замка, защищающего точку $$$p$$$. Обратите внимание, что если одно подмножество может быть соединено более чем одним способом, чтобы покрыть точку, то оно считается только один раз.</p><p>Пусть $$$f(p)$$$ будет количеством подмножеств из $$$4$$$-х точек, которые могут покрыть точку $$$p$$$. Пожалуйста, посчитайте сумму $$$f(p)$$$ по всем точкам $$$p \in s$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$5 \le n \le 2\,500$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$-10^9 \le x_i, y_i \le 10^9$$$), которые обозначают координаты точки.</p><p>Гарантируется, что все точки различны и что нет трех коллинеарных точек.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму $$$f(p)$$$ по всем точкам $$$p \in 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 -1 0 1 0 -10 -1 10 -1 0 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 0 1 1 2 2 2 1 3 0 -1 -1 -2 -2 -2 -1 -3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 40</pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 588634631 265299215 -257682751 342279997 527377039 82412729 145077145 702473706 276067232 912883502 822614418 -514698233 280281434 -41461635 65985059 -827653144 188538640 592896147 -857422304 -529223472 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 213</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:54:12</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'812493206a4615f6',t:'MTY5NjY2NTI1Mi4wMzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u041a\u043e\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\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2500"]
https://codeforces.com/blog/entry/72804
<!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="17bb3c0a988bbcfabcfbab3b80b286ce"/> <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="Hello 2020 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>Hello 2020 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='17bb3c0a988bbcfabcfbab3b80b286ce'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F72804">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='17bb3c0a988bbcfabcfbab3b80b286ce'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:37:33</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:37:33</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div><div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='17bb3c0a988bbcfabcfbab3b80b286ce'/> <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/ko_osaga">ko_osaga</a></li> <li class="current selectedLava"><a href="/blog/ko_osaga">Blog</a></li> <li><a href="/teams/with/ko_osaga">Teams</a></li> <li><a href="/submissions/ko_osaga">Submissions</a></li> <li><a href="/groups/with/ko_osaga">Groups</a></li> <li><a href="/contests/with/ko_osaga">Contests</a></li> <li><a href="/contests/writer/ko_osaga">Problemsetting</a></li> <li><a href="/streams/ko_osaga">Streams</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ko_osaga" style="text-decoration:none;color:black !important;">ko_osaga's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="73334"> <div class="title"> <a href="/blog/entry/72804"> <p>Hello 2020 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a>, <a href="/topic/73334/en12">history</a>, <span class="format-humantime" title="Jan/04/2020 18:44">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>Since the Polygon tutorial system is currently broken, I will replace the editorial with PDF format. Sorry for the inconvenience!</p><p><a href="https://www.dropbox.com/s/ysttw748rvx46eb/Hello%202020.pdf?dl=0">Solution PDF</a></p><p>Problem A was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203276">Code</a></p><p>Problem B was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203332">Code</a></p><p>Problem C was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203721">Code</a></p><p>Problem D was authored by <a class="rated-user user-orange" href="/profile/nong" title="Master nong">nong</a>. <a href="https://codeforces.com/contest/1284/submission/68203704">Code</a></p><p>Problem E was authored by <a class="rated-user user-orange" href="/profile/ckw1140" title="Master ckw1140">ckw1140</a>. <a href="https://codeforces.com/contest/1284/submission/68203754">Code</a></p><p>Problem F was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203787">Code</a></p><p>Problem G was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203817">Code</a></p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1284" class="notice" style="text-decoration: none;">Hello 2020</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-38652-73334").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "38652", blogEntryId: "72804", 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-73334"><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'>+191</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-73334"><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/ko_osaga"><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/ko_osaga"> ko_osaga </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="Jan/04/2020 18:44">4 years ago</span> </li> <li> <a href="/blog/entry/72804#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/72804#comments"> 157 </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="78289"> <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 (143)</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="570690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SHZhang" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SHZhang" title="International Grandmaster SHZhang" class="rated-user user-red">SHZhang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570690" href="?#comment-570690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570690" class="CommentVoteFrame" data-commentRating="50" data-commentUserId="1150683" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+50</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570690"> <div class="moveup"> <div class="ttypography"><p>When I open the editorial for problem E, I see the editorial for problem C instead. Can the author fix this, please?</p></div> </div> </div> <div class="reply info"> <a class="comment-570690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570690"> <li> <div class="comment"> <table class="comment-table" commentId="570700" commentParentId="570690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570700" href="?#comment-570700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570700" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570700"> <div class="moveup"> <div class="ttypography"><p>Sorry, it's fixed now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570700"> <li> <div class="comment"> <table class="comment-table" commentId="598782" commentParentId="570700"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jokerwyt" style="position: relative;"> <img src='https://userpic.codeforces.org/555567/avatar/247d0346874bdbdd.jpg'/> </a> <div><a href="/profile/jokerwyt" title="Candidate Master jokerwyt" class="rated-user user-violet">jokerwyt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/07/2020 16:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-598782" href="?#comment-598782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570700" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="598782" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555567" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-598782"> <div class="moveup"> <div class="ttypography"><p>Challenge of problem E is nice, but i have no idea how to solve it. Could you provide the solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-598782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-598782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-598782"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/21August" style="position: relative;"> <img src='https://userpic.codeforces.org/452773/avatar/13e016fa74fb3308.jpg'/> </a> <div><a href="/profile/21August" title="Master 21August" class="rated-user user-orange">21August</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570691" href="?#comment-570691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570691" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="452773" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570691"> <div class="moveup"> <div class="ttypography"><p>You got it wrong for E.</p></div> </div> </div> <div class="reply info"> <a class="comment-570691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570691"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570695" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 18:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570695" href="?#comment-570695" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570695" 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-570695"> <div class="moveup"> <div class="ttypography"><p>Really liked problems B and C :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570695"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570706" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TimonKnigge" style="position: relative;"> <img src='https://userpic.codeforces.org/275246/avatar/debe81b88ed671c2.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/TimonKnigge" title="Master TimonKnigge" class="rated-user user-orange">TimonKnigge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570706" href="?#comment-570706" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570706" class="CommentVoteFrame" data-commentRating="86" data-commentUserId="275246" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+86</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570706"> <div class="moveup"> <div class="ttypography"><p>Problem D is a lot more intuitive if you interpret the input as a collection of rectangles, where you are asked if there is a pair of rectangles that overlaps on one axis but not the other. Then a scanline solution is obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-570706 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570706 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570706"> <li> <div class="comment"> <table class="comment-table" commentId="570804" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Skeef79" style="position: relative;"> <img src='https://userpic.codeforces.org/631759/avatar/3033511aaec49179.jpg'/> </a> <div><a href="/profile/Skeef79" title="Candidate Master Skeef79" class="rated-user user-violet">Skeef79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570804" href="?#comment-570804" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570804"> <div class="moveup"> <div class="ttypography"><p>Can you please give some good resources about scanline? </p></div> </div> </div> <div class="reply info"> <a class="comment-570804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570804"> <li> <div class="comment"> <table class="comment-table" commentId="570996" commentParentId="570804"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rezwan.Arefin01" style="position: relative;"> <img src='https://userpic.codeforces.org/358701/avatar/68ec3668b1ccc552.jpg'/> </a> <div><a href="/profile/Rezwan.Arefin01" title="Candidate Master Rezwan.Arefin01" class="rated-user user-violet">Rezwan.Arefin01</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570996" href="?#comment-570996" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570804" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570996" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="358701" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570996"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.topcoder.com/community/competitive-programming/tutorials/line-sweep-algorithms/">Topcoder Tutorials</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570996 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570996 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570996"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570807" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570807" href="?#comment-570807" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570807" class="CommentVoteFrame" data-commentRating="33" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+33</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570807"> <div class="moveup"> <div class="ttypography"><p>That was the original formulation. I came up with the conference statement to make this problem much natural ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-570807 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570807 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570807"> <li> <div class="comment"> <table class="comment-table" commentId="571201" commentParentId="570807"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ghoshsai5000" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ghoshsai5000" title="Pupil ghoshsai5000" class="rated-user user-green">ghoshsai5000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571201" href="?#comment-571201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570807" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571201" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="543439" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571201"> <div class="moveup"> <div class="ttypography"><p>This was eye-opening ! So, the input format is $$$x_1, x_2, y_1, y_2$$$ and we have to look for $$$2$$$ rectangles such that their $$$x$$$-axes coincide but their $$$y$$$ do not or the other way around. </p><p>First time, we sort by $$$x$$$ and for every new line segment we process, we keep track of all the line segments it inserts with. We will check if the corresponding $$$y$$$ of the line segment fits in the bounds of all the line segments it has intersected so far. </p> <ul> <li>$$$y_1$$$ should not be greater than the smallest $$$y_2$$$ seen so far.</li> <li>$$$y_2$$$ should not be lesser than the greatest $$$y_1$$$ seen so far.</li> </ul><p>If you could include this interpretation in the editorial, it would help in understanding a lot :)</p></div> </div> </div> <div class="reply info"> <a class="comment-571201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571201"> <li> <div class="comment"> <table class="comment-table" commentId="571683" commentParentId="571201"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 19:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571683" href="?#comment-571683" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571683" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571683" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571683"> <div class="moveup"> <div class="ttypography"><p>To be honest, I think it very much depends on what you're comfortable with (Specifically, users who love geometry would love this interpretation). For me, it was easier to visualize the problem in the current format (interval format), whereas it took me a while to grasp the rectangle interpretation. It is interesting to see how the problem can be solved in so similar ways for seemingly different interpretations.</p></div> </div> </div> <div class="reply info"> <a class="comment-571683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571683"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="574189" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sthfaceless" style="position: relative;"> <img src='https://userpic.codeforces.org/1176362/avatar/4480df56f05c4612.jpg'/> </a> <div><a href="/profile/sthfaceless" title="Candidate Master sthfaceless" class="rated-user user-violet">sthfaceless</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/18/2020 20:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-574189" href="?#comment-574189" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="574189" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1176362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-574189"> <div class="moveup"> <div class="ttypography"><p>I used it too :)</p></div> </div> </div> <div class="reply info"> <a class="comment-574189 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-574189 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-574189"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570710" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Radewoosh" style="position: relative;"> <img src='https://userpic.codeforces.org/147752/avatar/a91526f3bd0194e8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570710" href="?#comment-570710" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570710" class="CommentVoteFrame" data-commentRating="76" data-commentUserId="147752" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+76</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570710"> <div class="moveup"> <div class="ttypography"><p>When will we be able to submit?</p></div> </div> </div> <div class="reply info"> <a class="comment-570710 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570710 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570710"> <li> <div class="comment"> <table class="comment-table" commentId="570734" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570734" href="?#comment-570734" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570734" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-38" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570734"> <div class="moveup"> <div class="ttypography"><p>In most contests, submission window opens 2 hours after the contest I guess.</p></div> </div> </div> <div class="reply info"> <a class="comment-570734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570734"> <li> <div class="comment"> <table class="comment-table" commentId="570808" commentParentId="570734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WaterColor2037" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/WaterColor2037" title="Master WaterColor2037" class="rated-user user-orange">WaterColor2037</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570808" href="?#comment-570808" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570808" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="876428" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570808"> <div class="moveup"> <div class="ttypography"><p>Why people downvote this?</p></div> </div> </div> <div class="reply info"> <a class="comment-570808 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570808 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570808"> <li> <div class="comment"> <table class="comment-table" commentId="570811" commentParentId="570808"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:40">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570811" href="?#comment-570811" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570808" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570811" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570811"> <div class="moveup"> <div class="ttypography"><p>Because it isn't true. Usually you can submit a few minutes after system tests are over.</p></div> </div> </div> <div class="reply info"> <a class="comment-570811 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570811 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570811"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570748" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570748" href="?#comment-570748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570748" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570748"> <div class="moveup"> <div class="ttypography"><p>Now submission is open.</p></div> </div> </div> <div class="reply info"> <a class="comment-570748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570748"> <li> <div class="comment"> <table class="comment-table" commentId="570761" commentParentId="570748"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570761" href="?#comment-570761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570748" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570761" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570761"> <div class="moveup"> <div class="ttypography"><p>Exactly 2 hours :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570711" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570711" href="?#comment-570711" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570711" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570711"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/72725?#comment-570663">Randomised sol for D</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570711 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570711 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570711"> <li> <div class="comment"> <table class="comment-table" commentId="570714" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570714" href="?#comment-570714" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570714" class="CommentVoteFrame" data-commentRating="59" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+59</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570714"> <div class="moveup"> <div class="ttypography"><p>There is another randomized approach involving hashes. You may assign random number to each lecture and then calculate for each interval the xor of numbers assigned to intervals it intersects. Now you should check that every lecture has same hashes in first and second places...</p></div> </div> </div> <div class="reply info"> <a class="comment-570714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570714"> <li> <div class="comment"> <table class="comment-table" commentId="570730" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570730" href="?#comment-570730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570730"> <div class="moveup"> <div class="ttypography"><p>how do you calculate the xor of the intersections?</p></div> </div> </div> <div class="reply info"> <a class="comment-570730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570730"> <li> <div class="comment"> <table class="comment-table" commentId="570735" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570735" href="?#comment-570735" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570735" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570735" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570735"> <div class="moveup"> <div class="ttypography"><p>I think, scan-line should work. When the interval $$$[l_i,r_i]$$$ opens, you put $$$h_i$$$ in the position $$$r_i$$$ and when this interval closes you take the xor of all numbers on the $$$[l_i, \infty)$$$.</p><p>It should look like <a href="https://ideone.com/Dypu4W">this</a>, but it gets WA-6 and I'm to sleepy to debug it properly.</p></div> </div> </div> <div class="reply info"> <a class="comment-570735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570735"> <li> <div class="comment"> <table class="comment-table" commentId="570764" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570764" href="?#comment-570764" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570764" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570764"> <div class="moveup"> <div class="ttypography"><p>yeah I did same thing but i get wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570764"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571027" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bhj2001" style="position: relative;"> <img src='https://userpic.codeforces.org/602476/avatar/71790bb4a53d93d3.jpg'/> </a> <div><a href="/profile/Bhj2001" title="Master Bhj2001" class="rated-user user-orange">Bhj2001</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571027" href="?#comment-571027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="602476" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571027"> <div class="moveup"> <div class="ttypography"><p>the WA is not because of hash collision <br /> you missed the case when 2 intervals completely overlap</p></div> </div> </div> <div class="reply info"> <a class="comment-571027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571027"> <li> <div class="comment"> <table class="comment-table" commentId="571059" commentParentId="571027"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571059" href="?#comment-571059" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571027" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571059" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571059"> <div class="moveup"> <div class="ttypography"><p>Not really, I just made a silly typo in my segment tree code... I got it accepted now: <a href="/contest/1284/submission/68205086" title="Submission 68205086 by adamant">68205086</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571059 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571059 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571059"> <li> <div class="comment"> <table class="comment-table" commentId="576198" commentParentId="571059"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anodaram" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anodaram" title="International Master anodaram" class="rated-user user-orange">anodaram</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/29/2020 08:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576198" href="?#comment-576198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571059" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576198" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="1314285" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-576198"> <div class="moveup"> <div class="ttypography"><p>Segment Tree is more popular way than multiset for this problem, I think.</p></div> </div> </div> <div class="reply info"> <a class="comment-576198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576198"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570740" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amnesiac_dusk" style="position: relative;"> <img src='https://userpic.codeforces.org/630995/avatar/5c9b8d77d7e96eff.jpg'/> </a> <div><a href="/profile/amnesiac_dusk" title="Grandmaster amnesiac_dusk" class="rated-user user-red">amnesiac_dusk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570740" href="?#comment-570740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570740" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="630995" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570740"> <div class="moveup"> <div class="ttypography"><p>It can also be treated as hashing all maximal cliques of the interval graph which should be sufficient for checking the equality of the graphs as the graph is chordal. My code for reference <a href="/contest/1284/submission/68181402" title="Submission 68181402 by amnesiac_dusk">68181402</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570740"> <li> <div class="comment"> <table class="comment-table" commentId="571137" commentParentId="570740"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tejas_919" style="position: relative;"> <img src='https://userpic.codeforces.org/875719/avatar/25f822a14baf7fbf.jpg'/> </a> <div><a href="/profile/tejas_919" title="Master tejas_919" class="rated-user user-orange">tejas_919</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571137" href="?#comment-571137" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571137" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571137"> <div class="moveup"> <div class="ttypography"><p>Can you tell me where can I learn this stuff about graphs? It would be really helpful of you.</p></div> </div> </div> <div class="reply info"> <a class="comment-571137 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571137 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571137"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570799" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/staniewzki" style="position: relative;"> <img src='https://userpic.codeforces.org/838116/avatar/307490effa9e1ae7.jpg'/> </a> <div><a href="/profile/staniewzki" title="Grandmaster staniewzki" class="rated-user user-red">staniewzki</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570799" href="?#comment-570799" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570799" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838116" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570799"> <div class="moveup"> <div class="ttypography"><p>You can look at my submission, I kept two segment trees — in one i put the value of the lecture on the beggining of the lecture and in the other on the end. Then, for each lecture i checked for lectures than do not intersect, so lectures that have end before the current beggining and the same for other side. </p></div> </div> </div> <div class="reply info"> <a class="comment-570799 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570799 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570799"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571124" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nizil" style="position: relative;"> <img src='https://userpic.codeforces.org/250190/avatar/d1314e6f3fecc96f.jpg'/> </a> <div><a href="/profile/Nizil" title="Expert Nizil" class="rated-user user-blue">Nizil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571124" href="?#comment-571124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571124" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="250190" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571124"> <div class="moveup"> <div class="ttypography"><p>I have a rather neat code doing this that might help: <a href="/contest/1284/submission/68239280" title="Submission 68239280 by Nizil">68239280</a>. I used the formula:</p> <center>$$$\{\text{Lectures that intersect lecture $$$l$$$}\} = \{\text{Lectures that start before $$$l$$$ ends}\} \setminus \{\text{Lectures that end before $$$l$$$ starts}\}$$$</center><p>. Note that if a lecture ends before $$$l$$$ starts, then it also begins before $$$l$$$ ends so in the subtraction every element of the latter set is contained in the former set. Also note that we do a XOR both when we add and when we remove a set.</p></div> </div> </div> <div class="reply info"> <a class="comment-571124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571124"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570746" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570746" href="?#comment-570746" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570746" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570746" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570746"> <div class="moveup"> <div class="ttypography"><p>My solution uses hashes also :)</p><p>Let's calculate value $$$sumA=\sum_{i \, intersects \, j}(h_i\cdot h_j)$$$ by some modulo for segments in A and the same $$$sumB$$$ for segments in B. Here, $$$h_i$$$ are some random values. This can be calculated with scanline. The answer is &quot;YES&quot; iff $$$sumA=sumB$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570746 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570746 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570746"> <li> <div class="comment"> <table class="comment-table" commentId="570766" commentParentId="570746"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570766" href="?#comment-570766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570746" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570766"> <div class="moveup"> <div class="ttypography"><p>yeah me too but i got wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570766"> <li> <div class="comment"> <table class="comment-table" commentId="570861" commentParentId="570766"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570861" href="?#comment-570861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570766" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570861"> <div class="moveup"> <div class="ttypography"><p>Maybe my code will be helpful: <a href="/contest/1284/submission/68181544" title="Submission 68181544 by VladProg">68181544</a></p><p>It doesn't use any data structures. Only two scan lines.</p></div> </div> </div> <div class="reply info"> <a class="comment-570861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570861"> <li> <div class="comment"> <table class="comment-table" commentId="570871" commentParentId="570861"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570871" href="?#comment-570871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570871"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-570871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570871"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570903" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lemelisk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lemelisk" title="Master lemelisk" class="rated-user user-orange">lemelisk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570903" href="?#comment-570903" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570903" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="513315" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570903"> <div class="moveup"> <div class="ttypography"><p>You can just treat intersections as long number in binary notification (zero means no intersection with given index's segment, one means intersection) and use its remainder as hash. See my submission <a href="https://codeforces.com/contest/1284/submission/68191562">https://codeforces.com/contest/1284/submission/68191562</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570903 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570903 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570903"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571092" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571092" href="?#comment-571092" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571092" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571092"> <div class="moveup"> <div class="ttypography"><p>I just leave it here. I also assign random number to each lecture, and then calculate some hashes. But to avoid cases when one segment completely inside in other, I just took complement approach. I get hash of all segments that doesn't intersect with selected. They are those who ends before selected, or starts after selected. So, I have two BIT for each place: one for lectures ending at time X and one for lectures starting at time X. This is done with packed coordinates and four BIT for each set of random identifiers. <a href="/contest/1284/submission/68198554" title="Submission 68198554 by r57shell">68198554</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571092 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571092 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571092"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570994" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570994" href="?#comment-570994" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570994" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570994"> <div class="moveup"> <div class="ttypography"><p>Me too.</p></div> </div> </div> <div class="reply info"> <a class="comment-570994 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570994 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570994"> <li> <div class="comment"> <table class="comment-table" commentId="570995" commentParentId="570994"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570995" href="?#comment-570995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570994" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570995"> <div class="moveup"> <div class="ttypography"><p>My randomised solution also passed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570995"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570712" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/GyojunYoun" style="position: relative;"> <img src='https://userpic.codeforces.org/227186/avatar/84d3b7d6c6ddb05c.jpg'/> </a> <div><a href="/profile/GyojunYoun" title="Grandmaster GyojunYoun" class="rated-user user-red">GyojunYoun</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570712" href="?#comment-570712" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570712" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570712" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="227186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570712"> <div class="moveup"> <div class="ttypography"><p>Thank you for setting these wonderful problems. Unlike other geometry probs, E is so beautiful that I was impressed :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570712 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570712 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570712"> <li> <div class="comment"> <table class="comment-table" commentId="570805" commentParentId="570712"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mango_lassi" style="position: relative;"> <img src='https://userpic.codeforces.org/519408/avatar/69109d1881b4b829.jpg'/> </a> <div><a href="/profile/mango_lassi" title="International Grandmaster mango_lassi" class="rated-user user-red">mango_lassi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570805" href="?#comment-570805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570712" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-29" data-commentUserId="519408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570805"> <div class="moveup"> <div class="ttypography"><p>Just what part of E do you think is beautiful? I agree that the model solution doesn't seem bad, but that is only in comparison to how painful writing code for the not-totally-magic solutions is. A problem with many easy to find ugly solutions does not turn good from the existence of a beautiful solution that is very difficult to find.</p></div> </div> </div> <div class="reply info"> <a class="comment-570805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570805"> <li> <div class="comment"> <table class="comment-table" commentId="570812" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570812" href="?#comment-570812" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570812" class="CommentVoteFrame" data-commentRating="62" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+62</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570812"> <div class="moveup"> <div class="ttypography"><p>I don't get the point. If you failed to find good solution, then it's our fault?</p></div> </div> </div> <div class="reply info"> <a class="comment-570812 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570812 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570812"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570838" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570838" href="?#comment-570838" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570838" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570838" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570838"> <div class="moveup"> <div class="ttypography"><p>Well, I found it really interesting what you can solve it in $$$O(n^2)$$$. <a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a> is really similar problem and I believe it can only be solved in $$$O(n^3)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570838 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570838 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570838"> <li> <div class="comment"> <table class="comment-table" commentId="570840" commentParentId="570838"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570840" href="?#comment-570840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570838" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570840"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-red" href="/profile/OnionPringles" title="International Grandmaster OnionPringles">OnionPringles</a> told me about the $$$O(n^2\log n)$$$ solution of that problem. Of course, it's much harder than our problem's solution, in any aspect.</p></div> </div> </div> <div class="reply info"> <a class="comment-570840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570840"> <li> <div class="comment"> <table class="comment-table" commentId="570867" commentParentId="570840"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570867" href="?#comment-570867" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570867" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570867"> <div class="moveup"> <div class="ttypography"><p>After I found $$$3x_3+4x_4+5x_5$$$ I thought I need $$$x_5$$$... After 4 TLE attempts, I saw the magic :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570867 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570867 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570867"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570722" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iaNTU" style="position: relative;"> <img src='https://userpic.codeforces.org/568681/avatar/e2c4a458dc77ff9b.jpg'/> </a> <div><a href="/profile/iaNTU" title="International Master iaNTU" class="rated-user user-orange">iaNTU</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570722" href="?#comment-570722" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570722" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-15" data-commentUserId="568681" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570722"> <div class="moveup"> <div class="ttypography"><p>Seems like you don't understand what &quot;right after&quot; means.</p></div> </div> </div> <div class="reply info"> <a class="comment-570722 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570722 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570722"> <li> <div class="comment"> <table class="comment-table" commentId="570728" commentParentId="570722"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570728" href="?#comment-570728" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570722" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570728" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-16" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570728"> <div class="moveup"> <div class="ttypography"><p>Right after systest. I'm sorry for F.</p></div> </div> </div> <div class="reply info"> <a class="comment-570728 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570728 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570728"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570739" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570739" href="?#comment-570739" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570739" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570739"> <div class="moveup"> <div class="ttypography"><p>Does the following flow solution for F run in time?</p><p>Create three sets of nodes A, B, and C. A represents the first set of edges, C represents the second set of edges. We need to match as many nodes in A as we can with nodes in C. Set B represents all the nodes in the tree. Each node in A and C will be connected to the two nodes that the edge it represents in connected to. We then run flow from the nodes in A to the nodes in C.</p><p>This graph has O(n) edges and a max flow of O(n).</p></div> </div> </div> <div class="reply info"> <a class="comment-570739 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570739 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570739"> <li> <div class="comment"> <table class="comment-table" commentId="570749" commentParentId="570739"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570749" href="?#comment-570749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570739" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570749"> <div class="moveup"> <div class="ttypography"><p>Actually, nevermind, this just doesn't work</p></div> </div> </div> <div class="reply info"> <a class="comment-570749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570749"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570743" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/snorkel" style="position: relative;"> <img src='https://userpic.codeforces.org/1360865/avatar/4aa0ab75c5725b5.jpg'/> </a> <div><a href="/profile/snorkel" title="Expert snorkel" class="rated-user user-blue">snorkel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570743" href="?#comment-570743" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360865" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570743"> <div class="moveup"> <div class="ttypography"><p>When the codes will be available?</p></div> </div> </div> <div class="reply info"> <a class="comment-570743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570743"> <li> <div class="comment"> <table class="comment-table" commentId="570767" commentParentId="570743"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570767" href="?#comment-570767" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570743" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570767" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570767"> <div class="moveup"> <div class="ttypography"><p>Code is available now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570767"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570750" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570750" href="?#comment-570750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570750" class="CommentVoteFrame" data-commentRating="12" 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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570750"> <div class="moveup"> <div class="ttypography"><p>For F we can prove that answer always equals $$$n - 1$$$ easily using Hall theorem. Pick any $$$k$$$ edges in first tree, we want to prove that there are at least $$$k$$$ edges in the second tree which can be used to replace at least one of picked edges. Let's remove all picked edges from the tree, then it splits to $$$k + 1$$$ components. For each edge in the second tree let's draw an edge between components containing endpoints of the edge. Since the tree was connected before compressing edges it is still connected now, which means it has at least $$$k$$$ edges which are not self-loops, which means there are at least $$$k$$$ edges which can be used to replace one of picked edges.</p></div> </div> </div> <div class="reply info"> <a class="comment-570750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570750"> <li> <div class="comment"> <table class="comment-table" commentId="570752" commentParentId="570750"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 19:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570752" href="?#comment-570752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570750" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570752" 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-570752"> <div class="moveup"> <div class="ttypography"><p>Sadly this proof gives no clue on how to find the matching</p></div> </div> </div> <div class="reply info"> <a class="comment-570752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570752"> <li> <div class="comment"> <table class="comment-table" commentId="570774" commentParentId="570752"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570774" href="?#comment-570774" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570774" 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-570774"> <div class="moveup"> <div class="ttypography"><p>In my solution (tl;dr <a href="https://codeforces.com/blog/entry/72725?#comment-570604">here</a>), it just turns out while I'm looking for some characteristics of the matching that it is perfect, and the argument for that is kinda similar to Hall's theorem — it also deals with sets of edges in T2 and adjacent edges in T1. It doesn't seem to be particularly useful for finding a way to compute a matching quickly, though.</p></div> </div> </div> <div class="reply info"> <a class="comment-570774 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570774 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570774"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570772" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570772" href="?#comment-570772" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570772" class="CommentVoteFrame" data-commentRating="20" 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;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570772"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p><p>Pick a 1 edge (u, v) from the T1, s.t. u is the leaf in T1. We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A). We can find matching, (u, v) in T1 &amp; (u, w) in T2, and remove those edges. For all x($$$x \neq w$$$), if there is a edge (u, x) in T2, we change u to v. it means, remove (u, x) and add(v, x) (step B). As a result, we can remove vertexes u and reduce problem size by one(after operate, T2 remained as tree).</p><p>How to simulate? Bottleneck is the step B, changing (u, x) to (v, x). Therefore we don't change all edges, but simply remove (u, w) and add dummy edge (u, v). We have to find nearest non-dummy edge in step A, but it's all. We can easily do it by Link-Cut Tree</p></div> </div> </div> <div class="reply info"> <a class="comment-570772 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570772 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570772"> <li> <div class="comment"> <table class="comment-table" commentId="570782" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570782" href="?#comment-570782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570782" 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-570782"> <div class="moveup"> <div class="ttypography"><blockquote><p>We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A).</p> </blockquote><p>Tbh when you have this, there's no need for further tricks or LCT. Just HLD over T1, store not yet taken edges in each path in a set (ordered by depth), DFS over T2 and use HLD to simulate the process for each edge in T2. That's my solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-570782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570782"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570785" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OnionPringles" 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/OnionPringles" title="International Grandmaster OnionPringles" class="rated-user user-red">OnionPringles</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570785" href="?#comment-570785" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570785" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="360543" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570785"> <div class="moveup"> <div class="ttypography"><p>I solved step B by merging u,v in T2 by implementing union-find structure on LCT nodes. When merging u and v, cut all preferred children of u and v so that the children can go through union-find structure when they try to access the unpreferred parent. I think it is easy if you have a pre-written LCT code.</p></div> </div> </div> <div class="reply info"> <a class="comment-570785 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570785 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570785"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570791" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gamegame" style="position: relative;"> <img src='https://userpic.codeforces.org/352372/avatar/8717a5b44702348a.jpg'/> </a> <div><a href="/profile/gamegame" title="Legendary Grandmaster gamegame" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>amegame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570791" href="?#comment-570791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="352372" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570791"> <div class="moveup"> <div class="ttypography"><p>You can do binary lifting and dsu, which is much more easier to code than LCT/HLD</p></div> </div> </div> <div class="reply info"> <a class="comment-570791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570791"> <li> <div class="comment"> <table class="comment-table" commentId="571082" commentParentId="570791"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 12:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571082" href="?#comment-571082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570791" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571082" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571082"> <div class="moveup"> <div class="ttypography"><p>I had the same, but tbh in such contests it would be more preferable to just copy LCT.</p></div> </div> </div> <div class="reply info"> <a class="comment-571082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571082"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570884" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570884" href="?#comment-570884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570884" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570884"> <div class="moveup"> <div class="ttypography"><p>I updated my solution to F. It is my favorite in this problem set. Hope you liked it too!</p></div> </div> </div> <div class="reply info"> <a class="comment-570884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570884"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570783" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570783" href="?#comment-570783" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570783" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+61</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570783"> <div class="moveup"> <div class="ttypography"><p>Here is a more intuitive explanation for E. Sorry if it's mentioned already.</p><p>Fix the point $$$p$$$. Translate everything such that $$$p$$$ coincides with the origin. Sort all the other points counter-clockwise. We shall now find the number of quadruples of points that <em>don't</em> form a polygon containing $$$p$$$.</p><p>Now consider some point $$$s$$$. Consider the half-plane $$$H$$$ of points $$$t$$$ such that the cross product $$$s \wedge t$$$ is positive. For a quadrilateral with $$$s$$$ to contain $$$p$$$, it has to have at least one point from $$$H$$$ and at least one point not from $$$H$$$. Conversely, we will count the number of quadruples $$$(s, t_1, t_2, t_3)$$$ such that $$$t_1, t_2, t_3 \in H$$$. It is just the binomial coefficient $$$|H| \choose 3$$$.</p><p>Now do that for all $$$s$$$ and all corresponding $$$H$$$, in linear time, using the two pointers method.</p><p>With iterating over all $$$p$$$ and sorting, the complexity is $$$O (n^2 \log n)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570783 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570783 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570783"> <li> <div class="comment"> <table class="comment-table" commentId="571005" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLamarca" style="position: relative;"> <img src='https://userpic.codeforces.org/379329/avatar/842836a6a188aadb.jpg'/> </a> <div><a href="/profile/VLamarca" title="Master VLamarca" class="rated-user user-orange">VLamarca</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571005" href="?#comment-571005" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571005" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571005" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="379329" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571005"> <div class="moveup"> <div class="ttypography"><p>This solution works for any size of polygon right? For example if the problem was about triangles instead of quadrilaterals</p><p>thanks for sharing it btw </p></div> </div> </div> <div class="reply info"> <a class="comment-571005 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571005 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571005"> <li> <div class="comment"> <table class="comment-table" commentId="571175" commentParentId="571005"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571175" href="?#comment-571175" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571005" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571175" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571175"> <div class="moveup"> <div class="ttypography"><p>Looks like, yeah, the same argument about all points being in one half-plane would work for pentagons and more.</p><p>Now, if the problem asks for <em>convex</em> polygons, it gets trickier, even with quadrilaterals.</p></div> </div> </div> <div class="reply info"> <a class="comment-571175 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571175 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571175"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571064" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Simurgh" style="position: relative;"> <img src='https://userpic.codeforces.org/1365761/avatar/1d3d3be9bd64e4c9.jpg'/> </a> <div><a href="/profile/Simurgh" title="Expert Simurgh" class="rated-user user-blue">Simurgh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571064" href="?#comment-571064" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571064" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1365761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571064"> <div class="moveup"> <div class="ttypography"><p>Where can I learn more about cross products of vectors and how they can be used in geometry problems?</p></div> </div> </div> <div class="reply info"> <a class="comment-571064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571064"> <li> <div class="comment"> <table class="comment-table" commentId="571178" commentParentId="571064"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571178" href="?#comment-571178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571064" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571178"> <div class="moveup"> <div class="ttypography"><p>Basically, scalar product and cross product are similar in behavior to cosine and sine of angle between vectors, respectively. Their signs behave the same.</p><p>The upside is that, more often than not, we are given coordinates of points as integers (or rationals). And computing scalar and cross products can be done using integers only. So we don't have to resort to floating point and then deal with a whole additional class of errors because of loss of precision.</p><p>As for more general overview, a <a href="https://www.google.com/search?q=scalar+product+and+cross+product+in+computational+geometry">Google search</a> lands some nice articles on the first page.</p></div> </div> </div> <div class="reply info"> <a class="comment-571178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571178"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571093" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 13:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571093" href="?#comment-571093" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571093" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571093" class="CommentVoteFrame" data-commentRating="10" 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: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-571093"> <div class="moveup"> <div class="ttypography"><p>How can I actually easily find the sign of the cross product between two vectors? I got an idea of how to do it with the angle between them, but it seems ugly and probably prone to bugs.</p><p>Edit: I found a way on <a href="https://en.wikipedia.org/wiki/Cross_product#Computational_geometry">Wikipedia</a>, scroll down to the Computation Geometry section.</p></div> </div> </div> <div class="reply info"> <a class="comment-571093 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571093 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571093"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570787" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/undisputedAshu" style="position: relative;"> <img src='https://userpic.codeforces.org/327726/avatar/92b4b2153c6ba4e4.jpg'/> </a> <div><a href="/profile/undisputedAshu" title="Pupil undisputedAshu" class="rated-user user-green">undisputedAshu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570787" href="?#comment-570787" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570787" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="327726" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570787"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain for B</p><p>3</p><p>4 2 0 2 0</p><p>6 9 9 8 8 7 7</p><p>1 6</p><p>how is it 7?</p></div> </div> </div> <div class="reply info"> <a class="comment-570787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570787"> <li> <div class="comment"> <table class="comment-table" commentId="570793" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/djm03178" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/djm03178" title="Master djm03178" class="rated-user user-orange">djm03178</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570793" href="?#comment-570793" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570793" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="687688" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570793"> <div class="moveup"> <div class="ttypography"><p>Let's say a = [2,0,2,0], b = [9,9,8,8,7,7], c = [6], then the answers are: aa, ab, ac, ba, bb, ca, and cb.</p></div> </div> </div> <div class="reply info"> <a class="comment-570793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570793"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570794" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gol_en_05" style="position: relative;"> <img src='https://userpic.codeforces.org/838032/avatar/8167074e5c48a57d.jpg'/> </a> <div><a href="/profile/gol_en_05" title="Specialist gol_en_05" class="rated-user user-cyan">gol_en_05</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570794" href="?#comment-570794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570794" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570794"> <div class="moveup"> <div class="ttypography"><p>since 2 0 2 0 has an ascent.so total pairs are 3. 2 nd sequence does not have an ascent but pairs (2,2),(2,1) has ascent. similarly for 3rd sequence pairs(3,1) and(3,2) has ascent. so total 7 pairs are possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-570794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570794"> <li> <div class="comment"> <table class="comment-table" commentId="570904" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570904" href="?#comment-570904" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570904" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570904"> <div class="moveup"> <div class="ttypography"><p>I'm struggling to understand what does &quot;but pairs (2,2),(2,1) has ascent&quot; mean. Can you please elaborate? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-570904 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570904 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570904"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570916" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570916" href="?#comment-570916" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570916" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570916"> <div class="moveup"> <div class="ttypography"><p>Thanks I got it!</p></div> </div> </div> <div class="reply info"> <a class="comment-570916 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570916 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570916"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570795" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BOGDAN_" 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/BOGDAN_" title="Expert BOGDAN_" class="rated-user user-blue">BOGDAN_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570795" href="?#comment-570795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570795" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="635882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570795"> <div class="moveup"> <div class="ttypography"><p>Let 1, 2, 3 — indexes of arrays. Here is &quot;1 + 2&quot;</p><p>&quot;1 + 3&quot;</p><p>&quot;1 + 1&quot;</p><p>&quot;2 + 2&quot;</p><p>&quot;2 + 1&quot;</p><p>&quot;3 + 1&quot;</p><p>&quot;3 + 2&quot;</p><p>At all — answer 7.</p></div> </div> </div> <div class="reply info"> <a class="comment-570795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570803" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Wa-Automaton" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Wa-Automaton" title="Candidate Master Wa-Automaton" class="rated-user user-violet">Wa-Automaton</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570803" href="?#comment-570803" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570803" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570803" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1365147" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570803"> <div class="moveup"> <div class="ttypography"><p>For D, removing operation is at time ea_i + 1 ?</p><p>UPD: It's fixed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570803 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570803 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570803"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570816" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570816" href="?#comment-570816" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570816" 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="570816" 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-570816"> <div class="moveup"> <div class="ttypography"><p>D can be solved using &quot;Job scheduling &quot; algorithm. Initially we check all the intervals for both the venues individually,whether they overlap,if we get different answer,answer is &quot;NO&quot;.</p><p>If we get same answer and both timings of both venues don't overlap,then answer is &quot;YES&quot;.</p><p>If we get &quot;over-lap&quot; for both,there is a possibility that removing some lectures might make one venue overlapping and other non_overlapping</p><p>eg: 1 2 3 4</p> <pre>3 4 4 5 4 5 6 7</pre><p>In this case,we use job scheduling algorithm to find the largest no of lectures that can be present such that,lecture timings don't overlap for venue A.</p><p>Keep only those lectures for B,check if answer is different for both venues,do the same thing for venue B.</p><p><a href="/contest/1284/submission/68206806" title="Submission 68206806 by AjaySabarish">68206806</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570816 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570816 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570816"> <li> <div class="comment"> <table class="comment-table" commentId="571060" commentParentId="570816"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571060" href="?#comment-571060" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570816" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571060" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571060"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/AjaySabarish" title="Expert AjaySabarish">AjaySabarish</a> Hi, can you please explain the part about &quot;non over-lap&quot; in a little detail?How is there a possibility that removing some lectures might make one venue overlapping and other non_overlapping? I also thought about job scheduling algo but as mentioned in comments, did not consider such cases like finding interval in a and then checking them in b and vice versa. Do they both not give same result? </p></div> </div> </div> <div class="reply info"> <a class="comment-571060 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571060 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571060"> <li> <div class="comment"> <table class="comment-table" commentId="571066" commentParentId="571060"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 11:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571066" href="?#comment-571066" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571060" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571066" 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-571066"> <div class="moveup"> <div class="ttypography"><p>Sry there was a typo,now corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-571066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571066"> <li> <div class="comment"> <table class="comment-table" commentId="571198" commentParentId="571066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571198" href="?#comment-571198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571198"> <div class="moveup"> <div class="ttypography"><p>Still can you explain that point about removing some lectures?</p></div> </div> </div> <div class="reply info"> <a class="comment-571198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571198"> <li> <div class="comment"> <table class="comment-table" commentId="571219" commentParentId="571198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571219" href="?#comment-571219" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571219" 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-571219"> <div class="moveup"> <div class="ttypography"><p>Consider the above example,which I gave </p><p>3</p><p>1 2 3 4</p><p>3 4 4 5</p><p>4 5 6 7</p><p>Now,the timings overlap for both venues,but if you remove lecture 3,timings dont overlap for venue A but overlap for venue B.</p><p>This is the last case which I was talking about,now you have to use job scheduling to find the answer.</p><p>Find the highest number of non overlapping segments for A,it is lecture 1,2.</p><p>Now keep only these lectures for both venues,now the segments for B should also not overlap for &quot;not venue sensitive&quot;. But it is overlapping,so it is venue sensitive</p></div> </div> </div> <div class="reply info"> <a class="comment-571219 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571219 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571219"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570825" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SajidZakaria" style="position: relative;"> <img src='https://userpic.codeforces.org/553136/avatar/f6d8cc00ec65b842.jpg'/> </a> <div><a href="/profile/SajidZakaria" title="Candidate Master SajidZakaria" class="rated-user user-violet">SajidZakaria</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570825" href="?#comment-570825" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570825" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="553136" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570825"> <div class="moveup"> <div class="ttypography"><p>The test cases in D were very &quot;weak&quot;. My solution : <a href="/contest/1284/submission/68205621" title="Submission 68205621 by SajidZakaria">68205621</a></p><p>For very large N, it's enough to only check if each of the lectures have the same number of intersections in A and B. Taking advantage of the fact that it's hard to put up a test case that avoids being fooled that way.</p></div> </div> </div> <div class="reply info"> <a class="comment-570825 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570825 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570825"> <li> <div class="comment"> <table class="comment-table" commentId="634898" commentParentId="570825"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Prajwal_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Prajwal_" title="Expert Prajwal_" class="rated-user user-blue">Prajwal_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/02/2020 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-634898" href="?#comment-634898" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570825" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="634898" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360518" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-634898"> <div class="moveup"> <div class="ttypography"><p>but how will you calculate the intersections in O(n) time.Can you explain once more??</p></div> </div> </div> <div class="reply info"> <a class="comment-634898 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-634898 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-634898"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570829" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570829" href="?#comment-570829" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570829" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570829"> <div class="moveup"> <div class="ttypography"><p>Can you share other solutions to E? Except <a class="rated-user user-orange" href="/profile/Gassa" title="International Master Gassa">Gassa</a>'s (above)</p></div> </div> </div> <div class="reply info"> <a class="comment-570829 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570829 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570829"> <li> <div class="comment"> <table class="comment-table" commentId="570852" commentParentId="570829"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570852" href="?#comment-570852" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570829" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570852" 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="570852" class="CommentVoteFrame" data-commentRating="45" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+45</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570852"> <div class="moveup"> <div class="ttypography"><p>I'll put it short:</p> <ul> <li>(By <a class="rated-user user-red" href="/profile/kdh9949" title="International Grandmaster kdh9949">kdh9949</a> <a class="rated-user user-orange" href="/profile/jihoon" title="International Master jihoon">jihoon</a>) Find $$$f(p)$$$ for each point. You can see that the set can enclose $$$p$$$ iff its convex hull contains $$$p$$$. Checking the containment is hard, so sort by angle, and eliminate the set that does not contain $$$p$$$, which reduces to almost similar sweep with model code. I think this is the easiest solution to come up with.</li> <li>(By <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a>) The answer depends on the 2 * (number of convex quadrilaterals) + (number of concave quadrilaterals). We denote this number $$$A$$$. I think the answer is $$$(A - 2\binom{n}{4}) \times (n-4)/2$$$, or something like that. This problem is bit harder, so you need another type of angular sweep like JOI Open 2017 Bulldozer. I think this is more involved to code, but our great tester <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a> took exactly 12 minutes to AC this.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-570852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570852"> <li> <div class="comment"> <table class="comment-table" commentId="571006" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/NoLongerRed" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/NoLongerRed" title="Grandmaster NoLongerRed" class="rated-user user-red">NoLongerRed</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571006" href="?#comment-571006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571006" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="567645" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571006"> <div class="moveup"> <div class="ttypography"><p>My solution is pretty much the same as molamola's solution and I think it is not necessary to do a cool angular sweep:<br />Let $$$X$$$ be the number of $$$((A,B,C),D)$$$ such that $$$D$$$ lies in $$$ABC$$$ and $$$(A,B,C)$$$ is an unordered tuple. The answer is $$$(n-4)X/2$$$.<br />$$$X$$$ can be counted easily: fixing $$$D$$$ and sort other points by the angles, then do a bunch of lower bound.</p></div> </div> </div> <div class="reply info"> <a class="comment-571006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571006"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571012" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571012" href="?#comment-571012" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571012" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571012"> <div class="moveup"> <div class="ttypography"><p>Thanks for sharing. The solution in Editorial really beautiful, but I don't know. Is that possible to came up with such solution in ~1 hour?</p></div> </div> </div> <div class="reply info"> <a class="comment-571012 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571012 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571012"> <li> <div class="comment"> <table class="comment-table" commentId="571014" commentParentId="571012"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571014" href="?#comment-571014" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571012" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571014" 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="571014" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571014"> <div class="moveup"> <div class="ttypography"><p>Actually my solution submitted during the contest is exactly same as the tutorial solution. In fact, I tried to compute all of $$$x$$$, $$$y$$$, and $$$z$$$, so I double-counted not only the edges of the convex hull but also the diagonal edges, to obtain three linear equations.</p> <center>$$$ x + y + z = {n \choose 5} \\ 5x + 4y + 3z = sth \\ 5x + 6y + 7z = sth $$$</center><p>Unfortunately, this linear system was undetermined, and all I can get was $$$(y + 2z)$$$. That was when I felt quite disappointed. But surprisingly, the answer to the problem happened to be exactly $$$(y + 2z)$$$, so I could finally solve the problem.</p><p>At first, I thought I was lucky enough to find a solution with such unsolvable system. So I headed to this tutorial to read the &quot;official&quot; solution, only to find my solution again. Thanks to your question, I found it in the comments :-)</p><p><a href="/contest/1284/submission/68196878" title="Submission 68196878 by jo_on">68196878</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571014 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571014 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571014"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570830" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570830" href="?#comment-570830" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570830" class="CommentVoteFrame" data-commentRating="3" 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: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-570830"> <div class="moveup"> <div class="ttypography"><p>Just curious,did everyone who solved C in contest,prove the solution?It was not so obvious to me,deciphering and processing what a &quot;framed segment&quot; is,took a lot of time.</p><p>Finding pattern was quite difficult,as manually generating test case even for n=4 is difficult</p><p>Lot of people solved it,is there any other idea?</p></div> </div> </div> <div class="reply info"> <a class="comment-570830 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570830 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570830"> <li> <div class="comment"> <table class="comment-table" commentId="570899" commentParentId="570830"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570899" href="?#comment-570899" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570830" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570899" class="CommentVoteFrame" data-commentRating="2" 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:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570899"> <div class="moveup"> <div class="ttypography"><p>Hi, If you now know what a &quot;framed segment&quot; is, then try to formulate number of &quot;framed segment&quot; of a particular length for a given n. For example: if we want to count &quot;framed segement&quot; of length 1. Let's first consider all &quot;framed segment&quot; containing only digit 1. For this &quot;framed segment&quot; to be at leftmost, there are (n — 1)! permutations. Similar argument goes for its other positions as well. This gives us count : (n — 1)! * n. Now, there are total of n single digits like &quot;1&quot; which can make single length &quot;framed segement&quot;. Thus now count for all single length &quot;framed segement&quot; is : (n — 1)! * n * n (something missing?). I have tried to explain the solution with single length fragment above with some details missing which I think you will figure out. Please try to come-up with a general formulation for any &quot;framed segment&quot;length x for a given n. Summing it all up will give you the answer. Link to my submission : <a href="https://codeforces.com/contest/1284/submission/68187501">Here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570899 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570899 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570899"> <li> <div class="comment"> <table class="comment-table" commentId="570912" commentParentId="570899"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570912" href="?#comment-570912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570899" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570912" 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-570912"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot,I get the solution,but I am just curious about the high number of submissions,was it so obvious?did everyone actually prove it or used their intuition to get it?</p></div> </div> </div> <div class="reply info"> <a class="comment-570912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570912"> <li> <div class="comment"> <table class="comment-table" commentId="570917" commentParentId="570912"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570917" href="?#comment-570917" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570912" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570917" 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-570917"> <div class="moveup"> <div class="ttypography"><p>I guess that depends on one's way of counting up to the answer. And from the number of submissions, it feels like people are actually good at counting..:P</p></div> </div> </div> <div class="reply info"> <a class="comment-570917 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570917 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570917"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kiimak" style="position: relative;"> <img src='https://userpic.codeforces.org/780779/avatar/9d6b81e1dd625cd6.jpg'/> </a> <div><a href="/profile/kiimak" title="Candidate Master kiimak" class="rated-user user-violet">kiimak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570849" href="?#comment-570849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570849" 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="570849" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="780779" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570849"> <div class="moveup"> <div class="ttypography"><p>Hi, I think I found a test case for problem D where my solution gets accepted but it should be incorrect.</p> <pre><code>5 1 10 1 10 2 20 11 30 11 30 2 20 21 40 21 40 31 50 31 50 </code></pre><p>I've checked with the code given in the tutorial, the answer is NO, but my solution gives YES. <a href="/contest/1284/submission/68207409" title="Submission 68207409 by kiimak">68207409</a></p><p>I've modeled it as a graph and put an edge (u, v) if lecture u and v meet. I thought it would be enough to check two things for graph A and B (venue A and B)</p> <ul> <li>the number of degrees for each lecture</li> <li>the lecture set of each component</li> </ul><p>I've submitted it after the contest so it doesn't effect my ratings, but I thought it was worth mentioning.</p></div> </div> </div> <div class="reply info"> <a class="comment-570849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570849"> <li> <div class="comment"> <table class="comment-table" commentId="570891" commentParentId="570849"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ormlis" style="position: relative;"> <img src='https://userpic.codeforces.org/1250517/avatar/5b32008c179f4f98.jpg'/> </a> <div><a href="/profile/Ormlis" title="Legendary Grandmaster Ormlis" class="rated-user user-legendary"><span class="legendary-user-first-letter">O</span>rmlis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570891" href="?#comment-570891" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570891" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1250517" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570891"> <div class="moveup"> <div class="ttypography"><p>I made the same mistake. I tried to find a test case where this is not true, but I could not. Thanks you</p></div> </div> </div> <div class="reply info"> <a class="comment-570891 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570891 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570891"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DJoker99" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/DJoker99" title="Pupil DJoker99" class="rated-user user-green">DJoker99</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570865" href="?#comment-570865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570865" 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="570865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="886083" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570865"> <div class="moveup"> <div class="ttypography"><p>Solution for B [Best :- O(n) Worst :- O(nlogn)]</p><p><a href="https://codeforces.com/contest/1284/submission/68210022">https://codeforces.com/contest/1284/submission/68210022</a></p><p>The condition for a non-ascent sequence a and a non-ascen sequence b to form an ascenting sequence is</p><p><code>min(a) &lt;max(b)</code></p> <ol> <li>First traverse the lists and store max and min in two separate vectors.</li> <li>if a sequence has ascent ie if an element greater than current min or current max occurs then that sequence will always give an ascenting sequence hence do <code>cnt = cnt + 2*n-1</code> <code>n--;</code> because that sequence will form 2n-1 sequences on concatenation</li> <li><p>Sort the max and min vectors then use two pointer approach.</p></li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-570865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570865"> <li> <div class="comment"> <table class="comment-table" commentId="570973" commentParentId="570865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 00:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570973" href="?#comment-570973" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570865" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570973" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570973" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570973"> <div class="moveup"> <div class="ttypography"><p>Involving sort gives already nlogn solution) - <a href="https://codeforces.com/contest/1284/submission/68206308">my code</a> — P. S. I have similar solution, but simpler.</p></div> </div> </div> <div class="reply info"> <a class="comment-570973 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570973 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570973"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570877" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prateek_aries" style="position: relative;"> <img src='https://userpic.codeforces.org/780171/avatar/c6136d0edef16466.jpg'/> </a> <div><a href="/profile/prateek_aries" title="Expert prateek_aries" class="rated-user user-blue">prateek_aries</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570877" href="?#comment-570877" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570877" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="780171" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570877"> <div class="moveup"> <div class="ttypography"><p>Someone please explain me the meaning of the last statement in C. &quot;By observing that there exist exactly n−len+1 pairs with 1≤l≤r≤n,r−l+1=len, we can simply multiply this number for each length, giving a O(n) time solution.&quot; Please give any example.</p></div> </div> </div> <div class="reply info"> <a class="comment-570877 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570877 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570877"> <li> <div class="comment"> <table class="comment-table" commentId="570981" commentParentId="570877"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570981" href="?#comment-570981" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570877" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570981" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570981"> <div class="moveup"> <div class="ttypography"><p>Example of what is it about: </p><p>Consider n of 5 and len of 3</p> <ul> <li><p>1 2 3</p></li> <li><p>2 3 4</p></li> <li><p>3 4 5</p></li> </ul><p>Permutate each of them, and you will get all framed subarrays for n and len of the example. </p></div> </div> </div> <div class="reply info"> <a class="comment-570981 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570981 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570981"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570883" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/im_sanyam" style="position: relative;"> <img src='https://userpic.codeforces.org/605247/avatar/6943d67eaf1d4243.jpg'/> </a> <div><a href="/profile/im_sanyam" title="Expert im_sanyam" class="rated-user user-blue">im_sanyam</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570883" href="?#comment-570883" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570883" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="605247" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570883"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain to me the solution of problem C in a better and intuitive way?</p></div> </div> </div> <div class="reply info"> <a class="comment-570883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570883"> <li> <div class="comment"> <table class="comment-table" commentId="570902" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570902" href="?#comment-570902" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570902" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570902" 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-570902"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570902 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570902 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570902"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570911" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/meiniak" style="position: relative;"> <img src='https://userpic.codeforces.org/803808/avatar/924fee722719da18.jpg'/> </a> <div><a href="/profile/meiniak" title="Newbie meiniak" class="rated-user user-gray">meiniak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570911" href="?#comment-570911" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570911" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="803808" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570911"> <div class="moveup"> <div class="ttypography"><p>let's take n = 5. ar = [1,2,3,4,5] . Now iterate for all possible length of sub-array and count number of good sub-array for that length. k = 1, 2, 3 and so on.</p><p>let take say k = 2 and n = 5. So there are n-k+1 position possible to place k elements i.e If we consider [1,2] then we can place [1,2] in position _ 3 _ 4 _ 5 _ and you can select (n-k+1) elements from n elements to i.e [1,2] , [2,3] , [3,4] and [4,5] . So this is how we got (n-k+1) * (n-k+1) and now we just have to count number of possible permutation of k and (n-k) elements left which is nothing but k! and (n-k)! .** (n-k+1) * (n-k+1) * k! * (n-k)!** is the total answer</p></div> </div> </div> <div class="reply info"> <a class="comment-570911 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570911 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570911"> <li> <div class="comment"> <table class="comment-table" commentId="647624" commentParentId="570911"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lazy_learner" style="position: relative;"> <img src='https://userpic.codeforces.org/926934/avatar/1c97e4ddf06e9813.jpg'/> </a> <div><a href="/profile/lazy_learner" title="Newbie lazy_learner" class="rated-user user-gray">lazy_learner</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2020 08:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-647624" href="?#comment-647624" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570911" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="647624" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926934" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-647624"> <div class="moveup"> <div class="ttypography"><p>But would that not lead to overcounting.<br />Consider the case 3 (1 2) 4 5 and 3 1 2 (4 5).<br />These 2 permutations are same and will be counted twice, once when we consider 1,2 together and second when 4,5 are taken together.</p></div> </div> </div> <div class="reply info"> <a class="comment-647624 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-647624 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-647624"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570914" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rover1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rover1" title="Specialist rover1" class="rated-user user-cyan">rover1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570914" href="?#comment-570914" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570914" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1239447" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570914"> <div class="moveup"> <div class="ttypography"><p>If in question C, we have given a permutation of length n then we need to find happiness... Anyone want to share their approaches ..</p></div> </div> </div> <div class="reply info"> <a class="comment-570914 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570914 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570914"> <li> <div class="comment"> <table class="comment-table" commentId="570918" commentParentId="570914"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570918" href="?#comment-570918" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570914" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570918" 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-570918"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570918"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570927" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/M1v1savva1601" style="position: relative;"> <img src='https://userpic.codeforces.org/539005/avatar/21949389dc808e09.jpg'/> </a> <div><a href="/profile/M1v1savva1601" title="Master M1v1savva1601" class="rated-user user-orange">M1v1savva1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570927" href="?#comment-570927" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570927" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="539005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570927"> <div class="moveup"> <div class="ttypography"><p>Shouldn't it be <strong>eai + 1</strong> in D tutorial?</p></div> </div> </div> <div class="reply info"> <a class="comment-570927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570927"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570941" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AwakeAnay" style="position: relative;"> <img src='https://userpic.codeforces.org/666008/avatar/7043fde46ee0493c.jpg'/> </a> <div><a href="/profile/AwakeAnay" title="Grandmaster AwakeAnay" class="rated-user user-red">AwakeAnay</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 23:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570941" href="?#comment-570941" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="666008" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570941"> <div class="moveup"> <div class="ttypography"><p>I had a overkill solution for $$$D$$$ which led to a good data structures problem. While, others have provided much more elegant solutions, this reduced version is a good problem on its own and worth sharing.</p><p>Here's the problem:</p><p>You are given two sequences $$$a_i$$$ and $$$b_i$$$ of length $$$2N$$$ each. Each number from $$$1$$$ to $$$N$$$ appears exactly twice in both the sequences. You have to solve $$$Q$$$ queries of the following kind:</p><p>Given $$$l$$$, $$$r$$$, $$$x$$$ and $$$y$$$, find the set of distinct elements in $$$(l, r)$$$ in $$$a$$$ is exactly equal to the set of distinct elements in $$$(x, y)$$$ in $$$b$$$. That is, any number $$$u$$$ has an appearance in segment $$$(l, r)$$$ in $$$a$$$ if and only if it has an appearance in segment $$$(x, y)$$$ in $$$b$$$. Try to solve this online in $$$O((N+Q)\log(N))$$$.</p><p>Think of how you can reduce today's $$$D$$$ into this problem.</p><p>My code for today's D: <a href="/contest/1284/submission/68189310" title="Submission 68189310 by AwakeAnay">68189310</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570941"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570975" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/madhav_1999" style="position: relative;"> <img src='https://userpic.codeforces.org/594602/avatar/cad96e04d2a42e66.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/madhav_1999" title="Master madhav_1999" class="rated-user user-orange">madhav_1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570975" href="?#comment-570975" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570975" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="594602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570975"> <div class="moveup"> <div class="ttypography"><p>In D: &quot;Event removing interval [sbi, ebi] from S at time ebi+1.&quot;</p><p><a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a>, I think you made an error here, it should be eai + 1 instead</p></div> </div> </div> <div class="reply info"> <a class="comment-570975 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570975 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570975"> <li> <div class="comment"> <table class="comment-table" commentId="571032" commentParentId="570975"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571032" href="?#comment-571032" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570975" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571032" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571032"> <div class="moveup"> <div class="ttypography"><p>Sorry, fixed. </p></div> </div> </div> <div class="reply info"> <a class="comment-571032 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571032 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571032"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570982" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 02:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570982" href="?#comment-570982" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570982" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570982"> <div class="moveup"> <div class="ttypography"><p>Problem B can also be solved in $$$O(n)$$$. Be $$$asc$$$ the number of sequences that have an ascent. For each sequence, check if it's non-increasing. If it isn't any concatenation we do will have an ascent, so we can add $$$n$$$ to our answer and $$$1$$$ to $$$asc$$$. Now be $$$s$$$ a non-increasing sequence and let's set it as the right part of the concatenation. We will only have an ascent in the concatenation if the left part already has an ascent or has an element smaller than any element in $$$s$$$, specially it's maximum. We have $$$asc$$$ sequences of the first type, so that's easy, and for the second part we can precalculate it by creating an array $$$minfreq$$$ where we store the minimum of each non-increasing sequence in it's position (as $$$s_{i,j} &lt; 10^6$$$) and do a sweep from $$$1$$$ to $$$10^6$$$ to accumulate our sum ($$$minfreq[i] = minfreq[i-1] +minfreq[i]$$$). Now we have our answer for the second part in position $$$minfreq[max(s)-1]$$$, and we can just add both parts to our answer. Since we can precalculate $$$minfreq$$$, $$$max(s)$$$ and $$$asc$$$ in $$$O(n)$$$ and the answer can be calculated in $$$O(1)$$$ using our precalculations total complexity is $$$O(n)$$$ </p></div> </div> </div> <div class="reply info"> <a class="comment-570982 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570982 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570982"> <li> <div class="comment"> <table class="comment-table" commentId="570987" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dblark" style="position: relative;"> <img src='https://userpic.codeforces.org/693276/avatar/70323ef41e4c9add.jpg'/> </a> <div><a href="/profile/dblark" title="International Master dblark" class="rated-user user-orange">dblark</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 03:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570987" href="?#comment-570987" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570987" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="693276" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570987"> <div class="moveup"> <div class="ttypography"><p>Yeah, the same idea with you!</p></div> </div> </div> <div class="reply info"> <a class="comment-570987 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570987 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570987"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571037" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 08:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571037" href="?#comment-571037" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571037" class="CommentVoteFrame" data-commentRating="0" 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:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571037"> <div class="moveup"> <div class="ttypography"><p>I did the same, but this is not O(N). The time Complexity will be O(n + maxELE) where maxELE is the largest sequence element seen in input.</p><p>We were lucky that the constraint on that wasn't 10^9.</p><p>Also consider cases in which n = 5 but the elements are still very large, our code would still take lot of time to execute.</p></div> </div> </div> <div class="reply info"> <a class="comment-571037 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571037 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571037"> <li> <div class="comment"> <table class="comment-table" commentId="571654" commentParentId="571037"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 18:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571654" href="?#comment-571654" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571037" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571654" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571654"> <div class="moveup"> <div class="ttypography"><p>Yeah that's true, the editorial's solution is more general for that same reason</p></div> </div> </div> <div class="reply info"> <a class="comment-571654 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571654 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571654"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571551" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571551" href="?#comment-571551" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571551" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571551"> <div class="moveup"> <div class="ttypography"><p>I cant understand the minfreq[i]=minfreq[i−1]+minfreq[i] . can you explain me </p></div> </div> </div> <div class="reply info"> <a class="comment-571551 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571551 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571551"> <li> <div class="comment"> <table class="comment-table" commentId="571653" commentParentId="571551"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571653" href="?#comment-571653" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571551" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571653" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571653"> <div class="moveup"> <div class="ttypography"><p>It's called accumulated sum. Basically we want minfreq[i] to be the frequency of all numbers $$$\leq$$$ to i, so we need to push our previous array position to our current one, so that we also take into account the occurences of numbers &lt; i, and not just equal to i</p></div> </div> </div> <div class="reply info"> <a class="comment-571653 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571653 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571653"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571001" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Aguin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Aguin" title="Candidate Master Aguin" class="rated-user user-violet">Aguin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571001" href="?#comment-571001" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571001" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="297931" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571001"> <div class="moveup"> <div class="ttypography"><p>How to count different quadrilaterals in problem E?</p></div> </div> </div> <div class="reply info"> <a class="comment-571001 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571001 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571001"> <li> <div class="comment"> <table class="comment-table" commentId="571004" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571004" href="?#comment-571004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571004"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571004"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571007" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 05:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571007" href="?#comment-571007" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571007" class="CommentVoteFrame" data-commentRating="3" 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;">+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-571007"> <div class="moveup"> <div class="ttypography"><p>For example, for each pair of points $$$(i, j)$$$, we can find the number of points on one side of the line i-j ($$$a$$$), the number of points on the other side ($$$N-2-a$$$), sum that up, divide by 2 and subtract $$$2{N\choose 4}$$$. Why? For each 4-tuple of points, if one of them is inside the triangle formed by the other 3 (their convex hull is a triangle), we get 3 lines (inner point, some other point) that are counted here, and when their convex hull is a quadrilateral, we get 2 such lines — its diagonals; we subtract (2 * number of 4-tuples) to get the number of 4-tuples where one point is inside.</p><p>How to find these $$$a$$$ for each pair $$$(i, j)$$$ fast? Let's say that $$$i$$$ is fixed, sort all remaining points by their angle around point $$$i$$$, then consider a line that crosses $$$i$$$, start rotating it and whenever it crosses one of these points, update the current value of $$$a$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-571007 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571007 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571007"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571011" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571011" href="?#comment-571011" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571011" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571011"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> (<a href="/topic/73334/en9">previous revision</a>, <a href="/topic/73334/en10">new revision</a>, <a href="/topic/73334/diff/en9/en10">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-571011 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571011 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571011"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hd7" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Hd7" title="Specialist Hd7" class="rated-user user-cyan">Hd7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571018" href="?#comment-571018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571018" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="559666" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571018"> <div class="moveup"> <div class="ttypography"><p>Could anyone give me a more elaborated explanation for problem D, I didn't grasp the editorial at all.</p></div> </div> </div> <div class="reply info"> <a class="comment-571018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571031" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571031" href="?#comment-571031" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571031" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571031"> <div class="moveup"> <div class="ttypography"><p>Expected a matroid problem, as <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> took matroid class last semester XD</p></div> </div> </div> <div class="reply info"> <a class="comment-571031 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571031 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571031"> <li> <div class="comment"> <table class="comment-table" commentId="571033" commentParentId="571031"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571033" href="?#comment-571033" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571031" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571033" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571033"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/team/65651">matroid fan club!</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571033 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571033 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571033"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571040" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PouyaNavid" style="position: relative;"> <img src='https://userpic.codeforces.org/670316/avatar/c42e949ea38011da.jpg'/> </a> <div><a href="/profile/PouyaNavid" title="Master PouyaNavid" class="rated-user user-orange">PouyaNavid</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 09:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571040" href="?#comment-571040" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571040" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="670316" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571040"> <div class="moveup"> <div class="ttypography"><p>Hack Test for D <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a></p><p>4 1 10 51 60 2 20 44 52 3 40 43 45 42 45 50 50</p></div> </div> </div> <div class="reply info"> <a class="comment-571040 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571040 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571040"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571088" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hazyknight" style="position: relative;"> <img src='https://userpic.codeforces.org/537474/avatar/e2c88ee4c2562699.jpg'/> </a> <div><a href="/profile/Hazyknight" title="International Grandmaster Hazyknight" class="rated-user user-red">Hazyknight</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571088" href="?#comment-571088" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571088" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571088" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="537474" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571088"> <div class="moveup"> <div class="ttypography"><p>Actually, Problem G can be solved easily by matroid intersection. Consider two matroid M1(S,I),M2(S,I), S is the set of wall, M1 is a graph matroid , M2 is a matroid which any black cell has at least to side without wall. Code: <a href="https://codeforces.com/contest/1284/submission/68215804">https://codeforces.com/contest/1284/submission/68215804</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571088 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571088 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571088"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571128" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amstan" style="position: relative;"> <img src='https://userpic.codeforces.org/734003/avatar/344c500da9a98a7f.jpg'/> </a> <div><a href="/profile/amstan" title="Expert amstan" class="rated-user user-blue">amstan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571128" href="?#comment-571128" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571128" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="734003" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571128"> <div class="moveup"> <div class="ttypography"><p>Is there anyone who solved D using coordinate compression and prefix sum ? If so, could you please share your submission.</p></div> </div> </div> <div class="reply info"> <a class="comment-571128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571128"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571138" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HaoxuanXIE" style="position: relative;"> <img src='https://userpic.codeforces.org/1234114/avatar/fa4b56dfead7992e.jpg'/> </a> <div><a href="/profile/HaoxuanXIE" title="Expert HaoxuanXIE" class="rated-user user-blue">HaoxuanXIE</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571138" href="?#comment-571138" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571138" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1234114" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571138"> <div class="moveup"> <div class="ttypography"><p>Why does D need to check in two directions? If I check in one direction, I get wrong answer at 9th point. But I think it is appropriate to check in only one direction.</p></div> </div> </div> <div class="reply info"> <a class="comment-571138 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571138 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571138"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571145" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheeLooser" style="position: relative;"> <img src='https://userpic.codeforces.org/448032/avatar/d5dcfa8c5dbd255f.jpg'/> </a> <div><a href="/profile/TheeLooser" title="Expert TheeLooser" class="rated-user user-blue">TheeLooser</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571145" href="?#comment-571145" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571145" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="448032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571145"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> may as well check how many visits were made to <a href="https://codeforces.com/problemset/problem/1146/H">this</a> page and later to <a href="https://codeforces.com/blog/entry/66639">this</a> page in contest time</p></div> </div> </div> <div class="reply info"> <a class="comment-571145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571145"> <li> <div class="comment"> <table class="comment-table" commentId="571459" commentParentId="571145"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 22:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571459" href="?#comment-571459" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571145" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571459" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571459"> <div class="moveup"> <div class="ttypography"><p>How does that problem help?</p></div> </div> </div> <div class="reply info"> <a class="comment-571459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571459"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571509" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Petr" style="position: relative;"> <img src='https://userpic.codeforces.org/664/avatar/a113c1791cdcd2e1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Petr" title="Legendary Grandmaster Petr" class="rated-user user-legendary"><span class="legendary-user-first-letter">P</span>etr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 01:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571509" href="?#comment-571509" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571509" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="664" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571509"> <div class="moveup"> <div class="ttypography"><p>Re: &quot;Hopefully, the first 80 tests were good enough for the contest.&quot;</p><p>My <a href="https://codeforces.com/contest/1284/submission/68208450">random solution</a> fails on test 87 :) Great job making the tests indeed!</p></div> </div> </div> <div class="reply info"> <a class="comment-571509 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571509 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571509"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571522" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MubtasimShahriar" style="position: relative;"> <img src='https://userpic.codeforces.org/756984/avatar/9113baa4abf04299.jpg'/> </a> <div><a href="/profile/MubtasimShahriar" title="Pupil MubtasimShahriar" class="rated-user user-green">MubtasimShahriar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 05:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571522" href="?#comment-571522" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571522" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756984" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571522"> <div class="moveup"> <div class="ttypography"><p>In Problem D, why does this solution not work? My Solutions is this.</p><p>Sort lectures according to their start-ending time in both venue, Then decide every lecture if it intersects with others in their own venue.</p><p>If there is at least one lecture that make difference in intersecting in both venue, then Subset can not be made. So the answer is no. If every problem either intersects in both venue or does not intersect in both venue then answer is yes. Here is my implementation <a href="/contest/1284/submission/68294866" title="Submission 68294866 by MubtasimShahriar">68294866</a></p><p>Please someone enlighten me where I am misunderstanding.</p></div> </div> </div> <div class="reply info"> <a class="comment-571522 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571522 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571522"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571546" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SLIMSHADYNICK" style="position: relative;"> <img src='https://userpic.codeforces.org/598862/avatar/7629f1b29f0fe807.jpg'/> </a> <div><a href="/profile/SLIMSHADYNICK" title="Candidate Master SLIMSHADYNICK" class="rated-user user-violet">SLIMSHADYNICK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571546" href="?#comment-571546" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571546" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-13" data-commentUserId="598862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-571546"> <div class="moveup"> <div class="ttypography"><p>In problem D, I got wrong answer on test case 14. Can somebody please help.</p></div> </div> </div> <div class="reply info"> <a class="comment-571546 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571546 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571546"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572491" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ftiasch" style="position: relative;"> <img src='https://userpic.codeforces.org/506/avatar/c52be21fbeb4a450.jpg'/> </a> <div><a href="/profile/ftiasch" title="International Grandmaster ftiasch" class="rated-user user-red">ftiasch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/11/2020 00:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572491" href="?#comment-572491" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572491" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="506" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-572491"> <div class="moveup"> <div class="ttypography"><p>2020 begins with two matroid problems. XD</p><p>btw, Challenge in Problem F is called Strong Basis Exchange as in <a href="https://math.mit.edu/~goemans/18438F09/lec11.pdf">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-572491 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572491 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572491"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572780" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Akash79" style="position: relative;"> <img src='https://userpic.codeforces.org/776725/avatar/700a28ac96121584.jpg'/> </a> <div><a href="/profile/Akash79" title="Expert Akash79" class="rated-user user-blue">Akash79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 16:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572780" href="?#comment-572780" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572780" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="776725" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572780"> <div class="moveup"> <div class="ttypography"><p>I am not able to understand problem B's solution.. can anyone please help me out..??</p></div> </div> </div> <div class="reply info"> <a class="comment-572780 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572780 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572780"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 17:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572849" href="?#comment-572849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="572849" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="572849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572849"> <div class="moveup"> <div class="ttypography"><p>Why don't we have to consider the case when there's some period intersecting in A and not intersecting in B? Doesn't that mean that sometimes our code will say 'YES' but the answer is 'NO'. Why? <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a>. EDIT: Ok, I just didn't notice the part of the code where he does the same thing but reversed.</p></div> </div> </div> <div class="reply info"> <a class="comment-572849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572849"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572863" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 18:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572863" href="?#comment-572863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572863" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572863"> <div class="moveup"> <div class="ttypography"><p>What is the hash approach for the problem D?</p></div> </div> </div> <div class="reply info"> <a class="comment-572863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572863"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="576477" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anaksoleh" style="position: relative;"> <img src='https://userpic.codeforces.org/1170460/avatar/27d790d7abbbd3d9.jpg'/> </a> <div><a href="/profile/anaksoleh" title="Newbie anaksoleh" class="rated-user user-gray">anaksoleh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/30/2020 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576477" href="?#comment-576477" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576477" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170460" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-576477"> <div class="moveup"> <div class="ttypography"><p>there is a proof for C solution ?</p></div> </div> </div> <div class="reply info"> <a class="comment-576477 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576477 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576477"> <li> <div class="comment"> <table class="comment-table" commentId="673042" commentParentId="576477"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/XORring-Samurai" style="position: relative;"> <img src='https://userpic.codeforces.org/1384228/avatar/d0258d5ed6604923.jpg'/> </a> <div><a href="/profile/XORring-Samurai" title="Candidate Master XORring-Samurai" class="rated-user user-violet">XORring-Samurai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/02/2020 09:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-673042" href="?#comment-673042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-576477" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="673042" 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="673042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1384228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-673042"> <div class="moveup"> <div class="ttypography"><p>Here is something, that I could think of.</p><p>For each permutation, we have the same $$$r-l$$$. This value varies from $$$0$$$ to $$$n-1$$$ for all $$$n$$$. Now let us consider $$$r-l=d$$$, as a general case. </p><p>For each $$$n$$$, we have $$$n-d$$$ pairs of $$$[l, r]$$$, where $$$r-l=d$$$. Also for all numbers from $$$1$$$ to $$$n$$$, we have $$$n-d$$$ pairs of type $$$[i, j]$$$ such that $$$j-i=d$$$. </p><p>For a segment to be framed, all the other places for each $$$[l, r]$$$ must be occupied by each integer from $$$[i, j]$$$. Therefore, we have $$$d+1$$$ numbers to be arranged in this interval $$$[l, r]$$$ and $$$n-d-1$$$ to be arranged in $$$[1, l-1]$$$ and $$$[r+1, n]$$$. This can be done in $$$(d+1)! * (n-d-1)!$$$ ways. </p><p>But we have $$$n-d$$$ pairs of $$$[l, r]$$$ and $$$n-d$$$ pairs of $$$[i, j]$$$, each of which can occupy this segment. Therefore the answer becomes summation over all $$$d$$$ from $$$0$$$ to $$$n-1$$$: $$$ans = ans + (n-d) * (n-d) * (d+1)! * (n-d-1)!$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-673042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-673042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-673042"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606852" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ThakurSaab" style="position: relative;"> <img src='https://userpic.codeforces.org/1267713/avatar/7c6c4d7b58cddb96.jpg'/> </a> <div><a href="/profile/ThakurSaab" title="Expert ThakurSaab" class="rated-user user-blue">ThakurSaab</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 17:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606852" href="?#comment-606852" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606852" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1267713" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606852"> <div class="moveup"> <div class="ttypography"><p>In problem C , do we consider that the numbers inside a particular segment [l,r] could be different such that, max-min = r-l</p></div> </div> </div> <div class="reply info"> <a class="comment-606852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606852"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="689589" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 07:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689589" href="?#comment-689589" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689589" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689589"> <div class="moveup"> <div class="ttypography"><p>In Problem D I added elements in the segment tree in the decreasing order of eai and then I queried for the previous range if the min of the ls and the maxr intersect with the particular index of a I am addding . I am getting a WA at Test Case 7 for this submission.</p><p>This is my submission link: <a href="https://codeforces.com/contest/1284/submission/91535000">https://codeforces.com/contest/1284/submission/91535000</a></p><p>Can somebody help me with this solution where I went wrong? </p><p>Or is there anyway I can look at the whole testcase then please reply here about how can I do that?</p></div> </div> </div> <div class="reply info"> <a class="comment-689589 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689589 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689589"> <li> <div class="comment"> <table class="comment-table" commentId="689595" commentParentId="689589"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 08:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689595" href="?#comment-689595" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-689589" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689595" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689595"> <div class="moveup"> <div class="ttypography"><p>Never Mind I made a silly typo in the cmp2 function.</p></div> </div> </div> <div class="reply info"> <a class="comment-689595 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689595 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689595"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="722358" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tanishq_code_c" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tanishq_code_c" title="Expert tanishq_code_c" class="rated-user user-blue">tanishq_code_c</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/17/2020 17:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-722358" href="?#comment-722358" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="722358" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1484322" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-722358"> <div class="moveup"> <div class="ttypography"><p>Hi, I am not able to understand the editorial for problem C. can anyone break it down in easy way please ? </p></div> </div> </div> <div class="reply info"> <a class="comment-722358 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-722358 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-722358"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="736312" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheOneYouWant" style="position: relative;"> <img src='https://userpic.codeforces.org/628619/avatar/c785428bde285c3.jpg'/> </a> <div><a href="/profile/TheOneYouWant" title="Master TheOneYouWant" class="rated-user user-orange">TheOneYouWant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/23/2020 05:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-736312" href="?#comment-736312" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="736312" class="CommentVoteFrame" data-commentRating="91" data-commentUserId="628619" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+91</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-736312"> <div class="moveup"> <div class="ttypography"><p>Hello, this seems to be broken (perhaps a sign of how the year 2020 has been so far)</p></div> </div> </div> <div class="reply info"> <a class="comment-736312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-736312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-736312"> <li> <div class="comment"> <table class="comment-table" commentId="737407" commentParentId="736312"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/27/2020 09:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-737407" href="?#comment-737407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-736312" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="737407" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-737407"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> please take a look, thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-737407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-737407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-737407"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741444" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/butterflies" style="position: relative;"> <img src='https://userpic.codeforces.org/1651561/avatar/33dfc9c16e5795ad.jpg'/> </a> <div><a href="/profile/butterflies" title="Specialist butterflies" class="rated-user user-cyan">butterflies</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741444" href="?#comment-741444" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="741444" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="741444" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1651561" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741444"> <div class="moveup"> <div class="ttypography"><p>This question relates to <a href="https://codeforces.com/contest/1284/problem/B">problem B</a>. I have a question with the second example input. Here is the input:</p> <pre><code>3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 </code></pre><p>I believe all arrays have an ascent. In the first array, the pair $$$(i, j) = (3, 4)$$$ works. ($$$a_3 = 0, a_4 = 2.$$$) In the second array, the pair $$$(i, j) = (1, 2)$$$ works. ($$$a_1 = 6, a_2 = 9.$$$) In the third array, the pair $$$(i,j) = (1, 2)$$$ works. ($$$a_1 = 1, a_2 = 6.$$$)</p><p>Thus, shouldn't all pairs of arrays in this case work? There are $$$9$$$ such pairs, but the answer to this should be $$$7.$$$ What is wrong with my reasoning here?</p></div> </div> </div> <div class="reply info"> <a class="comment-741444 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741444 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741444"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741445" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/beetroot" style="position: relative;"> <img src='https://userpic.codeforces.org/1503072/avatar/6668dbf5be4e4495.jpg'/> </a> <div><a href="/profile/beetroot" title="Expert beetroot" class="rated-user user-blue">beetroot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741445" href="?#comment-741445" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741445" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1503072" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741445"> <div class="moveup"> <div class="ttypography"><p>Editorials that didn't age well...</p></div> </div> </div> <div class="reply info"> <a class="comment-741445 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741445 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741445"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741475" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 07:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741475" href="?#comment-741475" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741475" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741475"> <div class="moveup"> <div class="ttypography"><p>Sorry for the issue with editorials. I think there is a timeout issue from Polygon. Since I can't resolve it, I will just rewrite it as a PDF form and upload here.</p></div> </div> </div> <div class="reply info"> <a class="comment-741475 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741475 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741475"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="797067" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/YPK" style="position: relative;"> <img src='https://userpic.codeforces.org/1489397/avatar/bd42de2aca7084dd.jpg'/> </a> <div><a href="/profile/YPK" title="Master YPK" class="rated-user user-orange">YPK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/29/2021 11:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-797067" href="?#comment-797067" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="797067" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="797067" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1489397" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-797067"> <div class="moveup"> <div class="ttypography"><p>Weak test cases for D. Consider the following test case </p> <pre><code>3 1 3 1 2 4 6 4 5 5 7 2 3 </code></pre><p>My accepted solution gives YES but the answer is NO.</p></div> </div> </div> <div class="reply info"> <a class="comment-797067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-797067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-797067"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="891199" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav04" style="position: relative;"> <img src='https://userpic.codeforces.org/2093148/avatar/b05253879beed26d.jpg'/> </a> <div><a href="/profile/abhinav04" title="Specialist abhinav04" class="rated-user user-cyan">abhinav04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/27/2022 11:56">19 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-891199" href="?#comment-891199" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="891199" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="2093148" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-891199"> <div class="moveup"> <div class="ttypography"><p>In case someone needs help with problem B, this might help.</p> <div class="spoiler"><b class="spoiler-title">submission</b><div class="spoiler-content" style="display: none;"><p><a href="https://codeforces.com/contest/1284/submission/147841447">https://codeforces.com/contest/1284/submission/147841447</a></p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-891199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-891199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-891199"> </ul> </div> <br/> <div id="editBox-78289" 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 firstPreview78289 = true; var lastPreviewContent78289 = ''; 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=78289] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=78289] 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-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, 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:27:29</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81288aad58e60057',t:'MTY5NjcwNjg0OS42NzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1284F
1284
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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Новая социальная сеть (НСС) от Donghyun содержит $$$n$$$ пользователей с номерами $$$1, 2, \ldots, n$$$. Их сеть представляет собой <span class="tex-font-style-it">дерево</span>, поэтому между пользователем существует $$$n-1$$$ прямых соединений. Каждый пользователь может связаться с другим пользователем, используя некоторую последовательность прямых соединений. Мы будем обозначать эту первичную сеть как $$$T_1$$$.</p><p>Чтобы предотвратить возможную поломку сервера, Donghyun создал резервную сеть $$$T_2$$$, которая соединяет тех же $$$n$$$ пользователей как дерево. Если система выходит из строя, ровно одно ребро $$$e \in T_1$$$ становится непригодным для использования. В этом случае Donghyun защитит ребро $$$e$$$, выбрав другое ребро $$$f \in T_2$$$, и добавит его в существующую сеть. Это новое ребро должно сделать сеть опять связной.</p><p>Donghyun хочет выбрать заменяющее ребро $$$f \in T_2$$$ для максимально возможного количества ребер $$$e \in T_1$$$. Однако, поскольку резервная сеть $$$T_2$$$ является хрупкой, $$$f \in T_2$$$ может быть выбрано в качестве замещающего ребра для не более одного ребра в $$$T_1$$$. С этим ограничением Donghyun хочет защитить как можно больше ребер в $$$T_1$$$.</p><p>Формально, пусть $$$E(T)$$$ — множество ребер дерева $$$T$$$. Рассмотрим двудольный граф с двумя долями $$$E(T_1)$$$ и $$$E(T_2)$$$. Для $$$e \in E(T_1), f \in E(T_2)$$$, существует ребро, соединяющее $$$\{e, f\}$$$ тогда и только тогда, когда граф $$$T_1 - \{e\} + \{f\}$$$ — дерево. Вы должны найти максимальное паросочетание в этом двудольном графе.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 250\,000$$$) — размер обоих деревьев. </p><p>В следующих $$$n-1$$$ строках записано по два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$). Эти два числа обозначают ребро из $$$T_1$$$.</p><p>В следующих $$$n-1$$$ строках записано по два целых числа $$$c_i$$$ и $$$d_i$$$ ($$$1 \le c_i, d_i \le n$$$). Эти два числа обозначают ребро из $$$T_2$$$. </p><p>Гарантируется, что оба этих множества ребер — это деревья на $$$n$$$ вершинах.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите целое число $$$m$$$ ($$$0 \leq m &lt; n$$$), размер максимального по размеру паросочетания.</p><p>В следующих $$$m$$$ строках выведите по четыре целых числа $$$a_i, b_i, c_i, d_i$$$. Эти четыре целых числа описывают, что ребро $$$(a_i, b_i)$$$ из $$$T_1$$$ объединено в пару с ребром $$$(c_i, d_i)$$$ из $$$T_2$$$.</p><p>Все выведенные ребра должны принадлежать соответствующим деревьям, и все выведенные ребра одного дерева должны быть различными. Если убирают ребро $$$(a_i, b_i)$$$ из $$$T_1$$$ и добавляют ребро $$$(c_i, d_i)$$$ из $$$T_2$$$, то сеть должна оставаться связной. Порядок выведенных пар и порядок вершин внутри ребер не имеет значения.</p><p>Если есть несколько возможных решений, вы можете вывести любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 2 3 4 3 1 3 2 4 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 2 4 2 2 1 1 3 4 3 1 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 2 4 3 4 4 5 1 2 1 3 1 4 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 2 1 1 2 3 4 1 3 4 2 1 4 5 4 1 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 9 7 9 2 8 2 1 7 5 4 7 2 4 9 6 3 9 1 8 4 8 2 9 9 5 7 6 1 3 4 6 5 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 4 2 9 2 9 7 6 7 5 7 5 9 6 9 4 6 8 2 8 4 3 9 3 5 2 1 1 8 7 4 1 3 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="bcf85ef635142e6e25fc2bffa7fd6108"/> <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="844107ee75ef6ee8a5d433a0bcfbbda150cb7f74"/> <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='bcf85ef635142e6e25fc2bffa7fd6108'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1284%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='bcf85ef635142e6e25fc2bffa7fd6108'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1284">Hello 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='bcf85ef635142e6e25fc2bffa7fd6108'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1284/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Паросочетания, теорема Кёнига, вершинные и реберные покрытия в двудольных графах"> паросочетания </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='bcf85ef635142e6e25fc2bffa7fd6108'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="508367"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bcf85ef635142e6e25fc2bffa7fd6108'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="508367"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72725" title="Hello 2020" target="_blank">Hello 2020 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10228" resourceName="Hello 2020" resourceManual="true" src="//codeforces.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/72804" title="Hello 2020 Editorial" target="_blank">Hello 2020 Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10239" resourceName="Hello 2020 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/1284">Задачи</a></li> <li><a href="/contest/1284/submit">Отослать</a></li> <li><a href="/contest/1284/my">Мои посылки</a></li> <li><a href="/contest/1284/status">Статус</a></li> <li><a href="/contest/1284/hacks">Взломы</a></li> <li><a href="/contest/1284/room/1">Комната</a></li> <li><a href="/contest/1284/standings">Положение</a></li> <li><a href="/contest/1284/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_76b8418d5baaa4ac63136514579b39f20d70afcf"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Новая социальная сеть (НСС) от Donghyun содержит $$$n$$$ пользователей с номерами $$$1, 2, \ldots, n$$$. Их сеть представляет собой <span class="tex-font-style-it">дерево</span>, поэтому между пользователем существует $$$n-1$$$ прямых соединений. Каждый пользователь может связаться с другим пользователем, используя некоторую последовательность прямых соединений. Мы будем обозначать эту первичную сеть как $$$T_1$$$.</p><p>Чтобы предотвратить возможную поломку сервера, Donghyun создал резервную сеть $$$T_2$$$, которая соединяет тех же $$$n$$$ пользователей как дерево. Если система выходит из строя, ровно одно ребро $$$e \in T_1$$$ становится непригодным для использования. В этом случае Donghyun защитит ребро $$$e$$$, выбрав другое ребро $$$f \in T_2$$$, и добавит его в существующую сеть. Это новое ребро должно сделать сеть опять связной.</p><p>Donghyun хочет выбрать заменяющее ребро $$$f \in T_2$$$ для максимально возможного количества ребер $$$e \in T_1$$$. Однако, поскольку резервная сеть $$$T_2$$$ является хрупкой, $$$f \in T_2$$$ может быть выбрано в качестве замещающего ребра для не более одного ребра в $$$T_1$$$. С этим ограничением Donghyun хочет защитить как можно больше ребер в $$$T_1$$$.</p><p>Формально, пусть $$$E(T)$$$ — множество ребер дерева $$$T$$$. Рассмотрим двудольный граф с двумя долями $$$E(T_1)$$$ и $$$E(T_2)$$$. Для $$$e \in E(T_1), f \in E(T_2)$$$, существует ребро, соединяющее $$$\{e, f\}$$$ тогда и только тогда, когда граф $$$T_1 - \{e\} + \{f\}$$$ — дерево. Вы должны найти максимальное паросочетание в этом двудольном графе.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 250\,000$$$) — размер обоих деревьев. </p><p>В следующих $$$n-1$$$ строках записано по два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$). Эти два числа обозначают ребро из $$$T_1$$$.</p><p>В следующих $$$n-1$$$ строках записано по два целых числа $$$c_i$$$ и $$$d_i$$$ ($$$1 \le c_i, d_i \le n$$$). Эти два числа обозначают ребро из $$$T_2$$$. </p><p>Гарантируется, что оба этих множества ребер — это деревья на $$$n$$$ вершинах.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите целое число $$$m$$$ ($$$0 \leq m &lt; n$$$), размер максимального по размеру паросочетания.</p><p>В следующих $$$m$$$ строках выведите по четыре целых числа $$$a_i, b_i, c_i, d_i$$$. Эти четыре целых числа описывают, что ребро $$$(a_i, b_i)$$$ из $$$T_1$$$ объединено в пару с ребром $$$(c_i, d_i)$$$ из $$$T_2$$$.</p><p>Все выведенные ребра должны принадлежать соответствующим деревьям, и все выведенные ребра одного дерева должны быть различными. Если убирают ребро $$$(a_i, b_i)$$$ из $$$T_1$$$ и добавляют ребро $$$(c_i, d_i)$$$ из $$$T_2$$$, то сеть должна оставаться связной. Порядок выведенных пар и порядок вершин внутри ребер не имеет значения.</p><p>Если есть несколько возможных решений, вы можете вывести любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 2 3 4 3 1 3 2 4 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 2 4 2 2 1 1 3 4 3 1 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 2 4 3 4 4 5 1 2 1 3 1 4 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 2 1 1 2 3 4 1 3 4 2 1 4 5 4 1 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 9 7 9 2 8 2 1 7 5 4 7 2 4 9 6 3 9 1 8 4 8 2 9 9 5 7 6 1 3 4 6 5 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 4 2 9 2 9 7 6 7 5 7 5 9 6 9 4 6 8 2 8 4 3 9 3 5 2 1 1 8 7 4 1 3 </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:54: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:'81249328efe6165a',t:'MTY5NjY2NTI1My4zNDgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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\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", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3200"]
https://codeforces.com/blog/entry/72804
<!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="17bb3c0a988bbcfabcfbab3b80b286ce"/> <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="Hello 2020 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>Hello 2020 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='17bb3c0a988bbcfabcfbab3b80b286ce'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F72804">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='17bb3c0a988bbcfabcfbab3b80b286ce'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:37:33</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:37:33</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div><div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='17bb3c0a988bbcfabcfbab3b80b286ce'/> <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/ko_osaga">ko_osaga</a></li> <li class="current selectedLava"><a href="/blog/ko_osaga">Blog</a></li> <li><a href="/teams/with/ko_osaga">Teams</a></li> <li><a href="/submissions/ko_osaga">Submissions</a></li> <li><a href="/groups/with/ko_osaga">Groups</a></li> <li><a href="/contests/with/ko_osaga">Contests</a></li> <li><a href="/contests/writer/ko_osaga">Problemsetting</a></li> <li><a href="/streams/ko_osaga">Streams</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ko_osaga" style="text-decoration:none;color:black !important;">ko_osaga's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="73334"> <div class="title"> <a href="/blog/entry/72804"> <p>Hello 2020 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a>, <a href="/topic/73334/en12">history</a>, <span class="format-humantime" title="Jan/04/2020 18:44">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>Since the Polygon tutorial system is currently broken, I will replace the editorial with PDF format. Sorry for the inconvenience!</p><p><a href="https://www.dropbox.com/s/ysttw748rvx46eb/Hello%202020.pdf?dl=0">Solution PDF</a></p><p>Problem A was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203276">Code</a></p><p>Problem B was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203332">Code</a></p><p>Problem C was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203721">Code</a></p><p>Problem D was authored by <a class="rated-user user-orange" href="/profile/nong" title="Master nong">nong</a>. <a href="https://codeforces.com/contest/1284/submission/68203704">Code</a></p><p>Problem E was authored by <a class="rated-user user-orange" href="/profile/ckw1140" title="Master ckw1140">ckw1140</a>. <a href="https://codeforces.com/contest/1284/submission/68203754">Code</a></p><p>Problem F was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203787">Code</a></p><p>Problem G was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203817">Code</a></p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1284" class="notice" style="text-decoration: none;">Hello 2020</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-38652-73334").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "38652", blogEntryId: "72804", 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-73334"><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'>+191</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-73334"><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/ko_osaga"><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/ko_osaga"> ko_osaga </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="Jan/04/2020 18:44">4 years ago</span> </li> <li> <a href="/blog/entry/72804#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/72804#comments"> 157 </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="78289"> <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 (143)</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="570690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SHZhang" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SHZhang" title="International Grandmaster SHZhang" class="rated-user user-red">SHZhang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570690" href="?#comment-570690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570690" class="CommentVoteFrame" data-commentRating="50" data-commentUserId="1150683" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+50</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570690"> <div class="moveup"> <div class="ttypography"><p>When I open the editorial for problem E, I see the editorial for problem C instead. Can the author fix this, please?</p></div> </div> </div> <div class="reply info"> <a class="comment-570690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570690"> <li> <div class="comment"> <table class="comment-table" commentId="570700" commentParentId="570690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570700" href="?#comment-570700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570700" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570700"> <div class="moveup"> <div class="ttypography"><p>Sorry, it's fixed now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570700"> <li> <div class="comment"> <table class="comment-table" commentId="598782" commentParentId="570700"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jokerwyt" style="position: relative;"> <img src='https://userpic.codeforces.org/555567/avatar/247d0346874bdbdd.jpg'/> </a> <div><a href="/profile/jokerwyt" title="Candidate Master jokerwyt" class="rated-user user-violet">jokerwyt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/07/2020 16:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-598782" href="?#comment-598782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570700" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="598782" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555567" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-598782"> <div class="moveup"> <div class="ttypography"><p>Challenge of problem E is nice, but i have no idea how to solve it. Could you provide the solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-598782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-598782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-598782"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/21August" style="position: relative;"> <img src='https://userpic.codeforces.org/452773/avatar/13e016fa74fb3308.jpg'/> </a> <div><a href="/profile/21August" title="Master 21August" class="rated-user user-orange">21August</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570691" href="?#comment-570691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570691" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="452773" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570691"> <div class="moveup"> <div class="ttypography"><p>You got it wrong for E.</p></div> </div> </div> <div class="reply info"> <a class="comment-570691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570691"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570695" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 18:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570695" href="?#comment-570695" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570695" 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-570695"> <div class="moveup"> <div class="ttypography"><p>Really liked problems B and C :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570695"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570706" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TimonKnigge" style="position: relative;"> <img src='https://userpic.codeforces.org/275246/avatar/debe81b88ed671c2.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/TimonKnigge" title="Master TimonKnigge" class="rated-user user-orange">TimonKnigge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570706" href="?#comment-570706" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570706" class="CommentVoteFrame" data-commentRating="86" data-commentUserId="275246" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+86</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570706"> <div class="moveup"> <div class="ttypography"><p>Problem D is a lot more intuitive if you interpret the input as a collection of rectangles, where you are asked if there is a pair of rectangles that overlaps on one axis but not the other. Then a scanline solution is obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-570706 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570706 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570706"> <li> <div class="comment"> <table class="comment-table" commentId="570804" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Skeef79" style="position: relative;"> <img src='https://userpic.codeforces.org/631759/avatar/3033511aaec49179.jpg'/> </a> <div><a href="/profile/Skeef79" title="Candidate Master Skeef79" class="rated-user user-violet">Skeef79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570804" href="?#comment-570804" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570804"> <div class="moveup"> <div class="ttypography"><p>Can you please give some good resources about scanline? </p></div> </div> </div> <div class="reply info"> <a class="comment-570804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570804"> <li> <div class="comment"> <table class="comment-table" commentId="570996" commentParentId="570804"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rezwan.Arefin01" style="position: relative;"> <img src='https://userpic.codeforces.org/358701/avatar/68ec3668b1ccc552.jpg'/> </a> <div><a href="/profile/Rezwan.Arefin01" title="Candidate Master Rezwan.Arefin01" class="rated-user user-violet">Rezwan.Arefin01</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570996" href="?#comment-570996" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570804" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570996" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="358701" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570996"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.topcoder.com/community/competitive-programming/tutorials/line-sweep-algorithms/">Topcoder Tutorials</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570996 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570996 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570996"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570807" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570807" href="?#comment-570807" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570807" class="CommentVoteFrame" data-commentRating="33" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+33</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570807"> <div class="moveup"> <div class="ttypography"><p>That was the original formulation. I came up with the conference statement to make this problem much natural ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-570807 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570807 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570807"> <li> <div class="comment"> <table class="comment-table" commentId="571201" commentParentId="570807"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ghoshsai5000" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ghoshsai5000" title="Pupil ghoshsai5000" class="rated-user user-green">ghoshsai5000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571201" href="?#comment-571201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570807" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571201" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="543439" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571201"> <div class="moveup"> <div class="ttypography"><p>This was eye-opening ! So, the input format is $$$x_1, x_2, y_1, y_2$$$ and we have to look for $$$2$$$ rectangles such that their $$$x$$$-axes coincide but their $$$y$$$ do not or the other way around. </p><p>First time, we sort by $$$x$$$ and for every new line segment we process, we keep track of all the line segments it inserts with. We will check if the corresponding $$$y$$$ of the line segment fits in the bounds of all the line segments it has intersected so far. </p> <ul> <li>$$$y_1$$$ should not be greater than the smallest $$$y_2$$$ seen so far.</li> <li>$$$y_2$$$ should not be lesser than the greatest $$$y_1$$$ seen so far.</li> </ul><p>If you could include this interpretation in the editorial, it would help in understanding a lot :)</p></div> </div> </div> <div class="reply info"> <a class="comment-571201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571201"> <li> <div class="comment"> <table class="comment-table" commentId="571683" commentParentId="571201"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 19:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571683" href="?#comment-571683" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571683" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571683" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571683"> <div class="moveup"> <div class="ttypography"><p>To be honest, I think it very much depends on what you're comfortable with (Specifically, users who love geometry would love this interpretation). For me, it was easier to visualize the problem in the current format (interval format), whereas it took me a while to grasp the rectangle interpretation. It is interesting to see how the problem can be solved in so similar ways for seemingly different interpretations.</p></div> </div> </div> <div class="reply info"> <a class="comment-571683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571683"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="574189" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sthfaceless" style="position: relative;"> <img src='https://userpic.codeforces.org/1176362/avatar/4480df56f05c4612.jpg'/> </a> <div><a href="/profile/sthfaceless" title="Candidate Master sthfaceless" class="rated-user user-violet">sthfaceless</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/18/2020 20:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-574189" href="?#comment-574189" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="574189" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1176362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-574189"> <div class="moveup"> <div class="ttypography"><p>I used it too :)</p></div> </div> </div> <div class="reply info"> <a class="comment-574189 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-574189 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-574189"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570710" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Radewoosh" style="position: relative;"> <img src='https://userpic.codeforces.org/147752/avatar/a91526f3bd0194e8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570710" href="?#comment-570710" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570710" class="CommentVoteFrame" data-commentRating="76" data-commentUserId="147752" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+76</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570710"> <div class="moveup"> <div class="ttypography"><p>When will we be able to submit?</p></div> </div> </div> <div class="reply info"> <a class="comment-570710 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570710 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570710"> <li> <div class="comment"> <table class="comment-table" commentId="570734" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570734" href="?#comment-570734" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570734" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-38" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570734"> <div class="moveup"> <div class="ttypography"><p>In most contests, submission window opens 2 hours after the contest I guess.</p></div> </div> </div> <div class="reply info"> <a class="comment-570734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570734"> <li> <div class="comment"> <table class="comment-table" commentId="570808" commentParentId="570734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WaterColor2037" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/WaterColor2037" title="Master WaterColor2037" class="rated-user user-orange">WaterColor2037</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570808" href="?#comment-570808" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570808" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="876428" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570808"> <div class="moveup"> <div class="ttypography"><p>Why people downvote this?</p></div> </div> </div> <div class="reply info"> <a class="comment-570808 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570808 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570808"> <li> <div class="comment"> <table class="comment-table" commentId="570811" commentParentId="570808"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:40">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570811" href="?#comment-570811" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570808" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570811" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570811"> <div class="moveup"> <div class="ttypography"><p>Because it isn't true. Usually you can submit a few minutes after system tests are over.</p></div> </div> </div> <div class="reply info"> <a class="comment-570811 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570811 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570811"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570748" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570748" href="?#comment-570748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570748" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570748"> <div class="moveup"> <div class="ttypography"><p>Now submission is open.</p></div> </div> </div> <div class="reply info"> <a class="comment-570748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570748"> <li> <div class="comment"> <table class="comment-table" commentId="570761" commentParentId="570748"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570761" href="?#comment-570761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570748" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570761" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570761"> <div class="moveup"> <div class="ttypography"><p>Exactly 2 hours :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570711" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570711" href="?#comment-570711" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570711" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570711"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/72725?#comment-570663">Randomised sol for D</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570711 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570711 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570711"> <li> <div class="comment"> <table class="comment-table" commentId="570714" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570714" href="?#comment-570714" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570714" class="CommentVoteFrame" data-commentRating="59" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+59</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570714"> <div class="moveup"> <div class="ttypography"><p>There is another randomized approach involving hashes. You may assign random number to each lecture and then calculate for each interval the xor of numbers assigned to intervals it intersects. Now you should check that every lecture has same hashes in first and second places...</p></div> </div> </div> <div class="reply info"> <a class="comment-570714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570714"> <li> <div class="comment"> <table class="comment-table" commentId="570730" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570730" href="?#comment-570730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570730"> <div class="moveup"> <div class="ttypography"><p>how do you calculate the xor of the intersections?</p></div> </div> </div> <div class="reply info"> <a class="comment-570730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570730"> <li> <div class="comment"> <table class="comment-table" commentId="570735" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570735" href="?#comment-570735" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570735" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570735" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570735"> <div class="moveup"> <div class="ttypography"><p>I think, scan-line should work. When the interval $$$[l_i,r_i]$$$ opens, you put $$$h_i$$$ in the position $$$r_i$$$ and when this interval closes you take the xor of all numbers on the $$$[l_i, \infty)$$$.</p><p>It should look like <a href="https://ideone.com/Dypu4W">this</a>, but it gets WA-6 and I'm to sleepy to debug it properly.</p></div> </div> </div> <div class="reply info"> <a class="comment-570735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570735"> <li> <div class="comment"> <table class="comment-table" commentId="570764" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570764" href="?#comment-570764" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570764" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570764"> <div class="moveup"> <div class="ttypography"><p>yeah I did same thing but i get wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570764"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571027" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bhj2001" style="position: relative;"> <img src='https://userpic.codeforces.org/602476/avatar/71790bb4a53d93d3.jpg'/> </a> <div><a href="/profile/Bhj2001" title="Master Bhj2001" class="rated-user user-orange">Bhj2001</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571027" href="?#comment-571027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="602476" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571027"> <div class="moveup"> <div class="ttypography"><p>the WA is not because of hash collision <br /> you missed the case when 2 intervals completely overlap</p></div> </div> </div> <div class="reply info"> <a class="comment-571027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571027"> <li> <div class="comment"> <table class="comment-table" commentId="571059" commentParentId="571027"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571059" href="?#comment-571059" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571027" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571059" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571059"> <div class="moveup"> <div class="ttypography"><p>Not really, I just made a silly typo in my segment tree code... I got it accepted now: <a href="/contest/1284/submission/68205086" title="Submission 68205086 by adamant">68205086</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571059 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571059 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571059"> <li> <div class="comment"> <table class="comment-table" commentId="576198" commentParentId="571059"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anodaram" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anodaram" title="International Master anodaram" class="rated-user user-orange">anodaram</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/29/2020 08:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576198" href="?#comment-576198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571059" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576198" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="1314285" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-576198"> <div class="moveup"> <div class="ttypography"><p>Segment Tree is more popular way than multiset for this problem, I think.</p></div> </div> </div> <div class="reply info"> <a class="comment-576198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576198"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570740" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amnesiac_dusk" style="position: relative;"> <img src='https://userpic.codeforces.org/630995/avatar/5c9b8d77d7e96eff.jpg'/> </a> <div><a href="/profile/amnesiac_dusk" title="Grandmaster amnesiac_dusk" class="rated-user user-red">amnesiac_dusk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570740" href="?#comment-570740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570740" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="630995" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570740"> <div class="moveup"> <div class="ttypography"><p>It can also be treated as hashing all maximal cliques of the interval graph which should be sufficient for checking the equality of the graphs as the graph is chordal. My code for reference <a href="/contest/1284/submission/68181402" title="Submission 68181402 by amnesiac_dusk">68181402</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570740"> <li> <div class="comment"> <table class="comment-table" commentId="571137" commentParentId="570740"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tejas_919" style="position: relative;"> <img src='https://userpic.codeforces.org/875719/avatar/25f822a14baf7fbf.jpg'/> </a> <div><a href="/profile/tejas_919" title="Master tejas_919" class="rated-user user-orange">tejas_919</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571137" href="?#comment-571137" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571137" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571137"> <div class="moveup"> <div class="ttypography"><p>Can you tell me where can I learn this stuff about graphs? It would be really helpful of you.</p></div> </div> </div> <div class="reply info"> <a class="comment-571137 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571137 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571137"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570799" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/staniewzki" style="position: relative;"> <img src='https://userpic.codeforces.org/838116/avatar/307490effa9e1ae7.jpg'/> </a> <div><a href="/profile/staniewzki" title="Grandmaster staniewzki" class="rated-user user-red">staniewzki</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570799" href="?#comment-570799" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570799" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838116" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570799"> <div class="moveup"> <div class="ttypography"><p>You can look at my submission, I kept two segment trees — in one i put the value of the lecture on the beggining of the lecture and in the other on the end. Then, for each lecture i checked for lectures than do not intersect, so lectures that have end before the current beggining and the same for other side. </p></div> </div> </div> <div class="reply info"> <a class="comment-570799 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570799 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570799"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571124" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nizil" style="position: relative;"> <img src='https://userpic.codeforces.org/250190/avatar/d1314e6f3fecc96f.jpg'/> </a> <div><a href="/profile/Nizil" title="Expert Nizil" class="rated-user user-blue">Nizil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571124" href="?#comment-571124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571124" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="250190" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571124"> <div class="moveup"> <div class="ttypography"><p>I have a rather neat code doing this that might help: <a href="/contest/1284/submission/68239280" title="Submission 68239280 by Nizil">68239280</a>. I used the formula:</p> <center>$$$\{\text{Lectures that intersect lecture $$$l$$$}\} = \{\text{Lectures that start before $$$l$$$ ends}\} \setminus \{\text{Lectures that end before $$$l$$$ starts}\}$$$</center><p>. Note that if a lecture ends before $$$l$$$ starts, then it also begins before $$$l$$$ ends so in the subtraction every element of the latter set is contained in the former set. Also note that we do a XOR both when we add and when we remove a set.</p></div> </div> </div> <div class="reply info"> <a class="comment-571124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571124"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570746" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570746" href="?#comment-570746" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570746" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570746" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570746"> <div class="moveup"> <div class="ttypography"><p>My solution uses hashes also :)</p><p>Let's calculate value $$$sumA=\sum_{i \, intersects \, j}(h_i\cdot h_j)$$$ by some modulo for segments in A and the same $$$sumB$$$ for segments in B. Here, $$$h_i$$$ are some random values. This can be calculated with scanline. The answer is &quot;YES&quot; iff $$$sumA=sumB$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570746 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570746 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570746"> <li> <div class="comment"> <table class="comment-table" commentId="570766" commentParentId="570746"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570766" href="?#comment-570766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570746" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570766"> <div class="moveup"> <div class="ttypography"><p>yeah me too but i got wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570766"> <li> <div class="comment"> <table class="comment-table" commentId="570861" commentParentId="570766"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570861" href="?#comment-570861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570766" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570861"> <div class="moveup"> <div class="ttypography"><p>Maybe my code will be helpful: <a href="/contest/1284/submission/68181544" title="Submission 68181544 by VladProg">68181544</a></p><p>It doesn't use any data structures. Only two scan lines.</p></div> </div> </div> <div class="reply info"> <a class="comment-570861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570861"> <li> <div class="comment"> <table class="comment-table" commentId="570871" commentParentId="570861"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570871" href="?#comment-570871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570871"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-570871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570871"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570903" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lemelisk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lemelisk" title="Master lemelisk" class="rated-user user-orange">lemelisk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570903" href="?#comment-570903" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570903" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="513315" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570903"> <div class="moveup"> <div class="ttypography"><p>You can just treat intersections as long number in binary notification (zero means no intersection with given index's segment, one means intersection) and use its remainder as hash. See my submission <a href="https://codeforces.com/contest/1284/submission/68191562">https://codeforces.com/contest/1284/submission/68191562</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570903 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570903 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570903"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571092" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571092" href="?#comment-571092" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571092" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571092"> <div class="moveup"> <div class="ttypography"><p>I just leave it here. I also assign random number to each lecture, and then calculate some hashes. But to avoid cases when one segment completely inside in other, I just took complement approach. I get hash of all segments that doesn't intersect with selected. They are those who ends before selected, or starts after selected. So, I have two BIT for each place: one for lectures ending at time X and one for lectures starting at time X. This is done with packed coordinates and four BIT for each set of random identifiers. <a href="/contest/1284/submission/68198554" title="Submission 68198554 by r57shell">68198554</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571092 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571092 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571092"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570994" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570994" href="?#comment-570994" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570994" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570994"> <div class="moveup"> <div class="ttypography"><p>Me too.</p></div> </div> </div> <div class="reply info"> <a class="comment-570994 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570994 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570994"> <li> <div class="comment"> <table class="comment-table" commentId="570995" commentParentId="570994"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570995" href="?#comment-570995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570994" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570995"> <div class="moveup"> <div class="ttypography"><p>My randomised solution also passed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570995"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570712" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/GyojunYoun" style="position: relative;"> <img src='https://userpic.codeforces.org/227186/avatar/84d3b7d6c6ddb05c.jpg'/> </a> <div><a href="/profile/GyojunYoun" title="Grandmaster GyojunYoun" class="rated-user user-red">GyojunYoun</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570712" href="?#comment-570712" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570712" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570712" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="227186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570712"> <div class="moveup"> <div class="ttypography"><p>Thank you for setting these wonderful problems. Unlike other geometry probs, E is so beautiful that I was impressed :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570712 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570712 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570712"> <li> <div class="comment"> <table class="comment-table" commentId="570805" commentParentId="570712"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mango_lassi" style="position: relative;"> <img src='https://userpic.codeforces.org/519408/avatar/69109d1881b4b829.jpg'/> </a> <div><a href="/profile/mango_lassi" title="International Grandmaster mango_lassi" class="rated-user user-red">mango_lassi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570805" href="?#comment-570805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570712" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-29" data-commentUserId="519408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570805"> <div class="moveup"> <div class="ttypography"><p>Just what part of E do you think is beautiful? I agree that the model solution doesn't seem bad, but that is only in comparison to how painful writing code for the not-totally-magic solutions is. A problem with many easy to find ugly solutions does not turn good from the existence of a beautiful solution that is very difficult to find.</p></div> </div> </div> <div class="reply info"> <a class="comment-570805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570805"> <li> <div class="comment"> <table class="comment-table" commentId="570812" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570812" href="?#comment-570812" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570812" class="CommentVoteFrame" data-commentRating="62" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+62</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570812"> <div class="moveup"> <div class="ttypography"><p>I don't get the point. If you failed to find good solution, then it's our fault?</p></div> </div> </div> <div class="reply info"> <a class="comment-570812 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570812 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570812"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570838" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570838" href="?#comment-570838" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570838" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570838" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570838"> <div class="moveup"> <div class="ttypography"><p>Well, I found it really interesting what you can solve it in $$$O(n^2)$$$. <a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a> is really similar problem and I believe it can only be solved in $$$O(n^3)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570838 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570838 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570838"> <li> <div class="comment"> <table class="comment-table" commentId="570840" commentParentId="570838"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570840" href="?#comment-570840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570838" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570840"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-red" href="/profile/OnionPringles" title="International Grandmaster OnionPringles">OnionPringles</a> told me about the $$$O(n^2\log n)$$$ solution of that problem. Of course, it's much harder than our problem's solution, in any aspect.</p></div> </div> </div> <div class="reply info"> <a class="comment-570840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570840"> <li> <div class="comment"> <table class="comment-table" commentId="570867" commentParentId="570840"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570867" href="?#comment-570867" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570867" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570867"> <div class="moveup"> <div class="ttypography"><p>After I found $$$3x_3+4x_4+5x_5$$$ I thought I need $$$x_5$$$... After 4 TLE attempts, I saw the magic :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570867 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570867 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570867"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570722" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iaNTU" style="position: relative;"> <img src='https://userpic.codeforces.org/568681/avatar/e2c4a458dc77ff9b.jpg'/> </a> <div><a href="/profile/iaNTU" title="International Master iaNTU" class="rated-user user-orange">iaNTU</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570722" href="?#comment-570722" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570722" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-15" data-commentUserId="568681" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570722"> <div class="moveup"> <div class="ttypography"><p>Seems like you don't understand what &quot;right after&quot; means.</p></div> </div> </div> <div class="reply info"> <a class="comment-570722 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570722 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570722"> <li> <div class="comment"> <table class="comment-table" commentId="570728" commentParentId="570722"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570728" href="?#comment-570728" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570722" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570728" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-16" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570728"> <div class="moveup"> <div class="ttypography"><p>Right after systest. I'm sorry for F.</p></div> </div> </div> <div class="reply info"> <a class="comment-570728 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570728 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570728"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570739" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570739" href="?#comment-570739" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570739" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570739"> <div class="moveup"> <div class="ttypography"><p>Does the following flow solution for F run in time?</p><p>Create three sets of nodes A, B, and C. A represents the first set of edges, C represents the second set of edges. We need to match as many nodes in A as we can with nodes in C. Set B represents all the nodes in the tree. Each node in A and C will be connected to the two nodes that the edge it represents in connected to. We then run flow from the nodes in A to the nodes in C.</p><p>This graph has O(n) edges and a max flow of O(n).</p></div> </div> </div> <div class="reply info"> <a class="comment-570739 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570739 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570739"> <li> <div class="comment"> <table class="comment-table" commentId="570749" commentParentId="570739"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570749" href="?#comment-570749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570739" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570749"> <div class="moveup"> <div class="ttypography"><p>Actually, nevermind, this just doesn't work</p></div> </div> </div> <div class="reply info"> <a class="comment-570749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570749"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570743" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/snorkel" style="position: relative;"> <img src='https://userpic.codeforces.org/1360865/avatar/4aa0ab75c5725b5.jpg'/> </a> <div><a href="/profile/snorkel" title="Expert snorkel" class="rated-user user-blue">snorkel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570743" href="?#comment-570743" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360865" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570743"> <div class="moveup"> <div class="ttypography"><p>When the codes will be available?</p></div> </div> </div> <div class="reply info"> <a class="comment-570743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570743"> <li> <div class="comment"> <table class="comment-table" commentId="570767" commentParentId="570743"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570767" href="?#comment-570767" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570743" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570767" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570767"> <div class="moveup"> <div class="ttypography"><p>Code is available now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570767"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570750" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570750" href="?#comment-570750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570750" class="CommentVoteFrame" data-commentRating="12" 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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570750"> <div class="moveup"> <div class="ttypography"><p>For F we can prove that answer always equals $$$n - 1$$$ easily using Hall theorem. Pick any $$$k$$$ edges in first tree, we want to prove that there are at least $$$k$$$ edges in the second tree which can be used to replace at least one of picked edges. Let's remove all picked edges from the tree, then it splits to $$$k + 1$$$ components. For each edge in the second tree let's draw an edge between components containing endpoints of the edge. Since the tree was connected before compressing edges it is still connected now, which means it has at least $$$k$$$ edges which are not self-loops, which means there are at least $$$k$$$ edges which can be used to replace one of picked edges.</p></div> </div> </div> <div class="reply info"> <a class="comment-570750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570750"> <li> <div class="comment"> <table class="comment-table" commentId="570752" commentParentId="570750"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 19:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570752" href="?#comment-570752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570750" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570752" 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-570752"> <div class="moveup"> <div class="ttypography"><p>Sadly this proof gives no clue on how to find the matching</p></div> </div> </div> <div class="reply info"> <a class="comment-570752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570752"> <li> <div class="comment"> <table class="comment-table" commentId="570774" commentParentId="570752"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570774" href="?#comment-570774" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570774" 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-570774"> <div class="moveup"> <div class="ttypography"><p>In my solution (tl;dr <a href="https://codeforces.com/blog/entry/72725?#comment-570604">here</a>), it just turns out while I'm looking for some characteristics of the matching that it is perfect, and the argument for that is kinda similar to Hall's theorem — it also deals with sets of edges in T2 and adjacent edges in T1. It doesn't seem to be particularly useful for finding a way to compute a matching quickly, though.</p></div> </div> </div> <div class="reply info"> <a class="comment-570774 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570774 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570774"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570772" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570772" href="?#comment-570772" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570772" class="CommentVoteFrame" data-commentRating="20" 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;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570772"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p><p>Pick a 1 edge (u, v) from the T1, s.t. u is the leaf in T1. We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A). We can find matching, (u, v) in T1 &amp; (u, w) in T2, and remove those edges. For all x($$$x \neq w$$$), if there is a edge (u, x) in T2, we change u to v. it means, remove (u, x) and add(v, x) (step B). As a result, we can remove vertexes u and reduce problem size by one(after operate, T2 remained as tree).</p><p>How to simulate? Bottleneck is the step B, changing (u, x) to (v, x). Therefore we don't change all edges, but simply remove (u, w) and add dummy edge (u, v). We have to find nearest non-dummy edge in step A, but it's all. We can easily do it by Link-Cut Tree</p></div> </div> </div> <div class="reply info"> <a class="comment-570772 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570772 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570772"> <li> <div class="comment"> <table class="comment-table" commentId="570782" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570782" href="?#comment-570782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570782" 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-570782"> <div class="moveup"> <div class="ttypography"><blockquote><p>We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A).</p> </blockquote><p>Tbh when you have this, there's no need for further tricks or LCT. Just HLD over T1, store not yet taken edges in each path in a set (ordered by depth), DFS over T2 and use HLD to simulate the process for each edge in T2. That's my solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-570782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570782"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570785" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OnionPringles" 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/OnionPringles" title="International Grandmaster OnionPringles" class="rated-user user-red">OnionPringles</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570785" href="?#comment-570785" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570785" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="360543" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570785"> <div class="moveup"> <div class="ttypography"><p>I solved step B by merging u,v in T2 by implementing union-find structure on LCT nodes. When merging u and v, cut all preferred children of u and v so that the children can go through union-find structure when they try to access the unpreferred parent. I think it is easy if you have a pre-written LCT code.</p></div> </div> </div> <div class="reply info"> <a class="comment-570785 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570785 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570785"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570791" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gamegame" style="position: relative;"> <img src='https://userpic.codeforces.org/352372/avatar/8717a5b44702348a.jpg'/> </a> <div><a href="/profile/gamegame" title="Legendary Grandmaster gamegame" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>amegame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570791" href="?#comment-570791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="352372" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570791"> <div class="moveup"> <div class="ttypography"><p>You can do binary lifting and dsu, which is much more easier to code than LCT/HLD</p></div> </div> </div> <div class="reply info"> <a class="comment-570791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570791"> <li> <div class="comment"> <table class="comment-table" commentId="571082" commentParentId="570791"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 12:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571082" href="?#comment-571082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570791" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571082" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571082"> <div class="moveup"> <div class="ttypography"><p>I had the same, but tbh in such contests it would be more preferable to just copy LCT.</p></div> </div> </div> <div class="reply info"> <a class="comment-571082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571082"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570884" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570884" href="?#comment-570884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570884" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570884"> <div class="moveup"> <div class="ttypography"><p>I updated my solution to F. It is my favorite in this problem set. Hope you liked it too!</p></div> </div> </div> <div class="reply info"> <a class="comment-570884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570884"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570783" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570783" href="?#comment-570783" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570783" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+61</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570783"> <div class="moveup"> <div class="ttypography"><p>Here is a more intuitive explanation for E. Sorry if it's mentioned already.</p><p>Fix the point $$$p$$$. Translate everything such that $$$p$$$ coincides with the origin. Sort all the other points counter-clockwise. We shall now find the number of quadruples of points that <em>don't</em> form a polygon containing $$$p$$$.</p><p>Now consider some point $$$s$$$. Consider the half-plane $$$H$$$ of points $$$t$$$ such that the cross product $$$s \wedge t$$$ is positive. For a quadrilateral with $$$s$$$ to contain $$$p$$$, it has to have at least one point from $$$H$$$ and at least one point not from $$$H$$$. Conversely, we will count the number of quadruples $$$(s, t_1, t_2, t_3)$$$ such that $$$t_1, t_2, t_3 \in H$$$. It is just the binomial coefficient $$$|H| \choose 3$$$.</p><p>Now do that for all $$$s$$$ and all corresponding $$$H$$$, in linear time, using the two pointers method.</p><p>With iterating over all $$$p$$$ and sorting, the complexity is $$$O (n^2 \log n)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570783 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570783 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570783"> <li> <div class="comment"> <table class="comment-table" commentId="571005" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLamarca" style="position: relative;"> <img src='https://userpic.codeforces.org/379329/avatar/842836a6a188aadb.jpg'/> </a> <div><a href="/profile/VLamarca" title="Master VLamarca" class="rated-user user-orange">VLamarca</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571005" href="?#comment-571005" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571005" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571005" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="379329" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571005"> <div class="moveup"> <div class="ttypography"><p>This solution works for any size of polygon right? For example if the problem was about triangles instead of quadrilaterals</p><p>thanks for sharing it btw </p></div> </div> </div> <div class="reply info"> <a class="comment-571005 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571005 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571005"> <li> <div class="comment"> <table class="comment-table" commentId="571175" commentParentId="571005"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571175" href="?#comment-571175" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571005" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571175" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571175"> <div class="moveup"> <div class="ttypography"><p>Looks like, yeah, the same argument about all points being in one half-plane would work for pentagons and more.</p><p>Now, if the problem asks for <em>convex</em> polygons, it gets trickier, even with quadrilaterals.</p></div> </div> </div> <div class="reply info"> <a class="comment-571175 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571175 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571175"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571064" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Simurgh" style="position: relative;"> <img src='https://userpic.codeforces.org/1365761/avatar/1d3d3be9bd64e4c9.jpg'/> </a> <div><a href="/profile/Simurgh" title="Expert Simurgh" class="rated-user user-blue">Simurgh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571064" href="?#comment-571064" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571064" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1365761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571064"> <div class="moveup"> <div class="ttypography"><p>Where can I learn more about cross products of vectors and how they can be used in geometry problems?</p></div> </div> </div> <div class="reply info"> <a class="comment-571064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571064"> <li> <div class="comment"> <table class="comment-table" commentId="571178" commentParentId="571064"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571178" href="?#comment-571178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571064" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571178"> <div class="moveup"> <div class="ttypography"><p>Basically, scalar product and cross product are similar in behavior to cosine and sine of angle between vectors, respectively. Their signs behave the same.</p><p>The upside is that, more often than not, we are given coordinates of points as integers (or rationals). And computing scalar and cross products can be done using integers only. So we don't have to resort to floating point and then deal with a whole additional class of errors because of loss of precision.</p><p>As for more general overview, a <a href="https://www.google.com/search?q=scalar+product+and+cross+product+in+computational+geometry">Google search</a> lands some nice articles on the first page.</p></div> </div> </div> <div class="reply info"> <a class="comment-571178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571178"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571093" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 13:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571093" href="?#comment-571093" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571093" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571093" class="CommentVoteFrame" data-commentRating="10" 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: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-571093"> <div class="moveup"> <div class="ttypography"><p>How can I actually easily find the sign of the cross product between two vectors? I got an idea of how to do it with the angle between them, but it seems ugly and probably prone to bugs.</p><p>Edit: I found a way on <a href="https://en.wikipedia.org/wiki/Cross_product#Computational_geometry">Wikipedia</a>, scroll down to the Computation Geometry section.</p></div> </div> </div> <div class="reply info"> <a class="comment-571093 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571093 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571093"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570787" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/undisputedAshu" style="position: relative;"> <img src='https://userpic.codeforces.org/327726/avatar/92b4b2153c6ba4e4.jpg'/> </a> <div><a href="/profile/undisputedAshu" title="Pupil undisputedAshu" class="rated-user user-green">undisputedAshu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570787" href="?#comment-570787" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570787" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="327726" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570787"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain for B</p><p>3</p><p>4 2 0 2 0</p><p>6 9 9 8 8 7 7</p><p>1 6</p><p>how is it 7?</p></div> </div> </div> <div class="reply info"> <a class="comment-570787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570787"> <li> <div class="comment"> <table class="comment-table" commentId="570793" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/djm03178" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/djm03178" title="Master djm03178" class="rated-user user-orange">djm03178</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570793" href="?#comment-570793" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570793" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="687688" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570793"> <div class="moveup"> <div class="ttypography"><p>Let's say a = [2,0,2,0], b = [9,9,8,8,7,7], c = [6], then the answers are: aa, ab, ac, ba, bb, ca, and cb.</p></div> </div> </div> <div class="reply info"> <a class="comment-570793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570793"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570794" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gol_en_05" style="position: relative;"> <img src='https://userpic.codeforces.org/838032/avatar/8167074e5c48a57d.jpg'/> </a> <div><a href="/profile/gol_en_05" title="Specialist gol_en_05" class="rated-user user-cyan">gol_en_05</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570794" href="?#comment-570794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570794" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570794"> <div class="moveup"> <div class="ttypography"><p>since 2 0 2 0 has an ascent.so total pairs are 3. 2 nd sequence does not have an ascent but pairs (2,2),(2,1) has ascent. similarly for 3rd sequence pairs(3,1) and(3,2) has ascent. so total 7 pairs are possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-570794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570794"> <li> <div class="comment"> <table class="comment-table" commentId="570904" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570904" href="?#comment-570904" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570904" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570904"> <div class="moveup"> <div class="ttypography"><p>I'm struggling to understand what does &quot;but pairs (2,2),(2,1) has ascent&quot; mean. Can you please elaborate? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-570904 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570904 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570904"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570916" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570916" href="?#comment-570916" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570916" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570916"> <div class="moveup"> <div class="ttypography"><p>Thanks I got it!</p></div> </div> </div> <div class="reply info"> <a class="comment-570916 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570916 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570916"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570795" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BOGDAN_" 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/BOGDAN_" title="Expert BOGDAN_" class="rated-user user-blue">BOGDAN_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570795" href="?#comment-570795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570795" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="635882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570795"> <div class="moveup"> <div class="ttypography"><p>Let 1, 2, 3 — indexes of arrays. Here is &quot;1 + 2&quot;</p><p>&quot;1 + 3&quot;</p><p>&quot;1 + 1&quot;</p><p>&quot;2 + 2&quot;</p><p>&quot;2 + 1&quot;</p><p>&quot;3 + 1&quot;</p><p>&quot;3 + 2&quot;</p><p>At all — answer 7.</p></div> </div> </div> <div class="reply info"> <a class="comment-570795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570803" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Wa-Automaton" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Wa-Automaton" title="Candidate Master Wa-Automaton" class="rated-user user-violet">Wa-Automaton</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570803" href="?#comment-570803" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570803" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570803" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1365147" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570803"> <div class="moveup"> <div class="ttypography"><p>For D, removing operation is at time ea_i + 1 ?</p><p>UPD: It's fixed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570803 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570803 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570803"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570816" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570816" href="?#comment-570816" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570816" 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="570816" 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-570816"> <div class="moveup"> <div class="ttypography"><p>D can be solved using &quot;Job scheduling &quot; algorithm. Initially we check all the intervals for both the venues individually,whether they overlap,if we get different answer,answer is &quot;NO&quot;.</p><p>If we get same answer and both timings of both venues don't overlap,then answer is &quot;YES&quot;.</p><p>If we get &quot;over-lap&quot; for both,there is a possibility that removing some lectures might make one venue overlapping and other non_overlapping</p><p>eg: 1 2 3 4</p> <pre>3 4 4 5 4 5 6 7</pre><p>In this case,we use job scheduling algorithm to find the largest no of lectures that can be present such that,lecture timings don't overlap for venue A.</p><p>Keep only those lectures for B,check if answer is different for both venues,do the same thing for venue B.</p><p><a href="/contest/1284/submission/68206806" title="Submission 68206806 by AjaySabarish">68206806</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570816 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570816 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570816"> <li> <div class="comment"> <table class="comment-table" commentId="571060" commentParentId="570816"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571060" href="?#comment-571060" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570816" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571060" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571060"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/AjaySabarish" title="Expert AjaySabarish">AjaySabarish</a> Hi, can you please explain the part about &quot;non over-lap&quot; in a little detail?How is there a possibility that removing some lectures might make one venue overlapping and other non_overlapping? I also thought about job scheduling algo but as mentioned in comments, did not consider such cases like finding interval in a and then checking them in b and vice versa. Do they both not give same result? </p></div> </div> </div> <div class="reply info"> <a class="comment-571060 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571060 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571060"> <li> <div class="comment"> <table class="comment-table" commentId="571066" commentParentId="571060"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 11:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571066" href="?#comment-571066" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571060" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571066" 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-571066"> <div class="moveup"> <div class="ttypography"><p>Sry there was a typo,now corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-571066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571066"> <li> <div class="comment"> <table class="comment-table" commentId="571198" commentParentId="571066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571198" href="?#comment-571198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571198"> <div class="moveup"> <div class="ttypography"><p>Still can you explain that point about removing some lectures?</p></div> </div> </div> <div class="reply info"> <a class="comment-571198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571198"> <li> <div class="comment"> <table class="comment-table" commentId="571219" commentParentId="571198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571219" href="?#comment-571219" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571219" 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-571219"> <div class="moveup"> <div class="ttypography"><p>Consider the above example,which I gave </p><p>3</p><p>1 2 3 4</p><p>3 4 4 5</p><p>4 5 6 7</p><p>Now,the timings overlap for both venues,but if you remove lecture 3,timings dont overlap for venue A but overlap for venue B.</p><p>This is the last case which I was talking about,now you have to use job scheduling to find the answer.</p><p>Find the highest number of non overlapping segments for A,it is lecture 1,2.</p><p>Now keep only these lectures for both venues,now the segments for B should also not overlap for &quot;not venue sensitive&quot;. But it is overlapping,so it is venue sensitive</p></div> </div> </div> <div class="reply info"> <a class="comment-571219 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571219 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571219"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570825" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SajidZakaria" style="position: relative;"> <img src='https://userpic.codeforces.org/553136/avatar/f6d8cc00ec65b842.jpg'/> </a> <div><a href="/profile/SajidZakaria" title="Candidate Master SajidZakaria" class="rated-user user-violet">SajidZakaria</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570825" href="?#comment-570825" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570825" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="553136" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570825"> <div class="moveup"> <div class="ttypography"><p>The test cases in D were very &quot;weak&quot;. My solution : <a href="/contest/1284/submission/68205621" title="Submission 68205621 by SajidZakaria">68205621</a></p><p>For very large N, it's enough to only check if each of the lectures have the same number of intersections in A and B. Taking advantage of the fact that it's hard to put up a test case that avoids being fooled that way.</p></div> </div> </div> <div class="reply info"> <a class="comment-570825 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570825 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570825"> <li> <div class="comment"> <table class="comment-table" commentId="634898" commentParentId="570825"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Prajwal_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Prajwal_" title="Expert Prajwal_" class="rated-user user-blue">Prajwal_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/02/2020 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-634898" href="?#comment-634898" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570825" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="634898" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360518" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-634898"> <div class="moveup"> <div class="ttypography"><p>but how will you calculate the intersections in O(n) time.Can you explain once more??</p></div> </div> </div> <div class="reply info"> <a class="comment-634898 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-634898 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-634898"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570829" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570829" href="?#comment-570829" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570829" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570829"> <div class="moveup"> <div class="ttypography"><p>Can you share other solutions to E? Except <a class="rated-user user-orange" href="/profile/Gassa" title="International Master Gassa">Gassa</a>'s (above)</p></div> </div> </div> <div class="reply info"> <a class="comment-570829 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570829 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570829"> <li> <div class="comment"> <table class="comment-table" commentId="570852" commentParentId="570829"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570852" href="?#comment-570852" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570829" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570852" 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="570852" class="CommentVoteFrame" data-commentRating="45" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+45</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570852"> <div class="moveup"> <div class="ttypography"><p>I'll put it short:</p> <ul> <li>(By <a class="rated-user user-red" href="/profile/kdh9949" title="International Grandmaster kdh9949">kdh9949</a> <a class="rated-user user-orange" href="/profile/jihoon" title="International Master jihoon">jihoon</a>) Find $$$f(p)$$$ for each point. You can see that the set can enclose $$$p$$$ iff its convex hull contains $$$p$$$. Checking the containment is hard, so sort by angle, and eliminate the set that does not contain $$$p$$$, which reduces to almost similar sweep with model code. I think this is the easiest solution to come up with.</li> <li>(By <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a>) The answer depends on the 2 * (number of convex quadrilaterals) + (number of concave quadrilaterals). We denote this number $$$A$$$. I think the answer is $$$(A - 2\binom{n}{4}) \times (n-4)/2$$$, or something like that. This problem is bit harder, so you need another type of angular sweep like JOI Open 2017 Bulldozer. I think this is more involved to code, but our great tester <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a> took exactly 12 minutes to AC this.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-570852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570852"> <li> <div class="comment"> <table class="comment-table" commentId="571006" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/NoLongerRed" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/NoLongerRed" title="Grandmaster NoLongerRed" class="rated-user user-red">NoLongerRed</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571006" href="?#comment-571006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571006" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="567645" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571006"> <div class="moveup"> <div class="ttypography"><p>My solution is pretty much the same as molamola's solution and I think it is not necessary to do a cool angular sweep:<br />Let $$$X$$$ be the number of $$$((A,B,C),D)$$$ such that $$$D$$$ lies in $$$ABC$$$ and $$$(A,B,C)$$$ is an unordered tuple. The answer is $$$(n-4)X/2$$$.<br />$$$X$$$ can be counted easily: fixing $$$D$$$ and sort other points by the angles, then do a bunch of lower bound.</p></div> </div> </div> <div class="reply info"> <a class="comment-571006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571006"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571012" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571012" href="?#comment-571012" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571012" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571012"> <div class="moveup"> <div class="ttypography"><p>Thanks for sharing. The solution in Editorial really beautiful, but I don't know. Is that possible to came up with such solution in ~1 hour?</p></div> </div> </div> <div class="reply info"> <a class="comment-571012 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571012 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571012"> <li> <div class="comment"> <table class="comment-table" commentId="571014" commentParentId="571012"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571014" href="?#comment-571014" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571012" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571014" 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="571014" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571014"> <div class="moveup"> <div class="ttypography"><p>Actually my solution submitted during the contest is exactly same as the tutorial solution. In fact, I tried to compute all of $$$x$$$, $$$y$$$, and $$$z$$$, so I double-counted not only the edges of the convex hull but also the diagonal edges, to obtain three linear equations.</p> <center>$$$ x + y + z = {n \choose 5} \\ 5x + 4y + 3z = sth \\ 5x + 6y + 7z = sth $$$</center><p>Unfortunately, this linear system was undetermined, and all I can get was $$$(y + 2z)$$$. That was when I felt quite disappointed. But surprisingly, the answer to the problem happened to be exactly $$$(y + 2z)$$$, so I could finally solve the problem.</p><p>At first, I thought I was lucky enough to find a solution with such unsolvable system. So I headed to this tutorial to read the &quot;official&quot; solution, only to find my solution again. Thanks to your question, I found it in the comments :-)</p><p><a href="/contest/1284/submission/68196878" title="Submission 68196878 by jo_on">68196878</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571014 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571014 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571014"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570830" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570830" href="?#comment-570830" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570830" class="CommentVoteFrame" data-commentRating="3" 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: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-570830"> <div class="moveup"> <div class="ttypography"><p>Just curious,did everyone who solved C in contest,prove the solution?It was not so obvious to me,deciphering and processing what a &quot;framed segment&quot; is,took a lot of time.</p><p>Finding pattern was quite difficult,as manually generating test case even for n=4 is difficult</p><p>Lot of people solved it,is there any other idea?</p></div> </div> </div> <div class="reply info"> <a class="comment-570830 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570830 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570830"> <li> <div class="comment"> <table class="comment-table" commentId="570899" commentParentId="570830"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570899" href="?#comment-570899" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570830" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570899" class="CommentVoteFrame" data-commentRating="2" 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:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570899"> <div class="moveup"> <div class="ttypography"><p>Hi, If you now know what a &quot;framed segment&quot; is, then try to formulate number of &quot;framed segment&quot; of a particular length for a given n. For example: if we want to count &quot;framed segement&quot; of length 1. Let's first consider all &quot;framed segment&quot; containing only digit 1. For this &quot;framed segment&quot; to be at leftmost, there are (n — 1)! permutations. Similar argument goes for its other positions as well. This gives us count : (n — 1)! * n. Now, there are total of n single digits like &quot;1&quot; which can make single length &quot;framed segement&quot;. Thus now count for all single length &quot;framed segement&quot; is : (n — 1)! * n * n (something missing?). I have tried to explain the solution with single length fragment above with some details missing which I think you will figure out. Please try to come-up with a general formulation for any &quot;framed segment&quot;length x for a given n. Summing it all up will give you the answer. Link to my submission : <a href="https://codeforces.com/contest/1284/submission/68187501">Here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570899 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570899 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570899"> <li> <div class="comment"> <table class="comment-table" commentId="570912" commentParentId="570899"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570912" href="?#comment-570912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570899" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570912" 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-570912"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot,I get the solution,but I am just curious about the high number of submissions,was it so obvious?did everyone actually prove it or used their intuition to get it?</p></div> </div> </div> <div class="reply info"> <a class="comment-570912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570912"> <li> <div class="comment"> <table class="comment-table" commentId="570917" commentParentId="570912"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570917" href="?#comment-570917" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570912" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570917" 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-570917"> <div class="moveup"> <div class="ttypography"><p>I guess that depends on one's way of counting up to the answer. And from the number of submissions, it feels like people are actually good at counting..:P</p></div> </div> </div> <div class="reply info"> <a class="comment-570917 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570917 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570917"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kiimak" style="position: relative;"> <img src='https://userpic.codeforces.org/780779/avatar/9d6b81e1dd625cd6.jpg'/> </a> <div><a href="/profile/kiimak" title="Candidate Master kiimak" class="rated-user user-violet">kiimak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570849" href="?#comment-570849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570849" 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="570849" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="780779" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570849"> <div class="moveup"> <div class="ttypography"><p>Hi, I think I found a test case for problem D where my solution gets accepted but it should be incorrect.</p> <pre><code>5 1 10 1 10 2 20 11 30 11 30 2 20 21 40 21 40 31 50 31 50 </code></pre><p>I've checked with the code given in the tutorial, the answer is NO, but my solution gives YES. <a href="/contest/1284/submission/68207409" title="Submission 68207409 by kiimak">68207409</a></p><p>I've modeled it as a graph and put an edge (u, v) if lecture u and v meet. I thought it would be enough to check two things for graph A and B (venue A and B)</p> <ul> <li>the number of degrees for each lecture</li> <li>the lecture set of each component</li> </ul><p>I've submitted it after the contest so it doesn't effect my ratings, but I thought it was worth mentioning.</p></div> </div> </div> <div class="reply info"> <a class="comment-570849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570849"> <li> <div class="comment"> <table class="comment-table" commentId="570891" commentParentId="570849"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ormlis" style="position: relative;"> <img src='https://userpic.codeforces.org/1250517/avatar/5b32008c179f4f98.jpg'/> </a> <div><a href="/profile/Ormlis" title="Legendary Grandmaster Ormlis" class="rated-user user-legendary"><span class="legendary-user-first-letter">O</span>rmlis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570891" href="?#comment-570891" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570891" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1250517" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570891"> <div class="moveup"> <div class="ttypography"><p>I made the same mistake. I tried to find a test case where this is not true, but I could not. Thanks you</p></div> </div> </div> <div class="reply info"> <a class="comment-570891 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570891 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570891"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DJoker99" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/DJoker99" title="Pupil DJoker99" class="rated-user user-green">DJoker99</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570865" href="?#comment-570865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570865" 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="570865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="886083" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570865"> <div class="moveup"> <div class="ttypography"><p>Solution for B [Best :- O(n) Worst :- O(nlogn)]</p><p><a href="https://codeforces.com/contest/1284/submission/68210022">https://codeforces.com/contest/1284/submission/68210022</a></p><p>The condition for a non-ascent sequence a and a non-ascen sequence b to form an ascenting sequence is</p><p><code>min(a) &lt;max(b)</code></p> <ol> <li>First traverse the lists and store max and min in two separate vectors.</li> <li>if a sequence has ascent ie if an element greater than current min or current max occurs then that sequence will always give an ascenting sequence hence do <code>cnt = cnt + 2*n-1</code> <code>n--;</code> because that sequence will form 2n-1 sequences on concatenation</li> <li><p>Sort the max and min vectors then use two pointer approach.</p></li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-570865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570865"> <li> <div class="comment"> <table class="comment-table" commentId="570973" commentParentId="570865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 00:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570973" href="?#comment-570973" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570865" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570973" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570973" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570973"> <div class="moveup"> <div class="ttypography"><p>Involving sort gives already nlogn solution) - <a href="https://codeforces.com/contest/1284/submission/68206308">my code</a> — P. S. I have similar solution, but simpler.</p></div> </div> </div> <div class="reply info"> <a class="comment-570973 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570973 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570973"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570877" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prateek_aries" style="position: relative;"> <img src='https://userpic.codeforces.org/780171/avatar/c6136d0edef16466.jpg'/> </a> <div><a href="/profile/prateek_aries" title="Expert prateek_aries" class="rated-user user-blue">prateek_aries</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570877" href="?#comment-570877" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570877" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="780171" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570877"> <div class="moveup"> <div class="ttypography"><p>Someone please explain me the meaning of the last statement in C. &quot;By observing that there exist exactly n−len+1 pairs with 1≤l≤r≤n,r−l+1=len, we can simply multiply this number for each length, giving a O(n) time solution.&quot; Please give any example.</p></div> </div> </div> <div class="reply info"> <a class="comment-570877 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570877 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570877"> <li> <div class="comment"> <table class="comment-table" commentId="570981" commentParentId="570877"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570981" href="?#comment-570981" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570877" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570981" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570981"> <div class="moveup"> <div class="ttypography"><p>Example of what is it about: </p><p>Consider n of 5 and len of 3</p> <ul> <li><p>1 2 3</p></li> <li><p>2 3 4</p></li> <li><p>3 4 5</p></li> </ul><p>Permutate each of them, and you will get all framed subarrays for n and len of the example. </p></div> </div> </div> <div class="reply info"> <a class="comment-570981 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570981 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570981"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570883" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/im_sanyam" style="position: relative;"> <img src='https://userpic.codeforces.org/605247/avatar/6943d67eaf1d4243.jpg'/> </a> <div><a href="/profile/im_sanyam" title="Expert im_sanyam" class="rated-user user-blue">im_sanyam</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570883" href="?#comment-570883" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570883" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="605247" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570883"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain to me the solution of problem C in a better and intuitive way?</p></div> </div> </div> <div class="reply info"> <a class="comment-570883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570883"> <li> <div class="comment"> <table class="comment-table" commentId="570902" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570902" href="?#comment-570902" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570902" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570902" 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-570902"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570902 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570902 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570902"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570911" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/meiniak" style="position: relative;"> <img src='https://userpic.codeforces.org/803808/avatar/924fee722719da18.jpg'/> </a> <div><a href="/profile/meiniak" title="Newbie meiniak" class="rated-user user-gray">meiniak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570911" href="?#comment-570911" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570911" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="803808" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570911"> <div class="moveup"> <div class="ttypography"><p>let's take n = 5. ar = [1,2,3,4,5] . Now iterate for all possible length of sub-array and count number of good sub-array for that length. k = 1, 2, 3 and so on.</p><p>let take say k = 2 and n = 5. So there are n-k+1 position possible to place k elements i.e If we consider [1,2] then we can place [1,2] in position _ 3 _ 4 _ 5 _ and you can select (n-k+1) elements from n elements to i.e [1,2] , [2,3] , [3,4] and [4,5] . So this is how we got (n-k+1) * (n-k+1) and now we just have to count number of possible permutation of k and (n-k) elements left which is nothing but k! and (n-k)! .** (n-k+1) * (n-k+1) * k! * (n-k)!** is the total answer</p></div> </div> </div> <div class="reply info"> <a class="comment-570911 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570911 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570911"> <li> <div class="comment"> <table class="comment-table" commentId="647624" commentParentId="570911"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lazy_learner" style="position: relative;"> <img src='https://userpic.codeforces.org/926934/avatar/1c97e4ddf06e9813.jpg'/> </a> <div><a href="/profile/lazy_learner" title="Newbie lazy_learner" class="rated-user user-gray">lazy_learner</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2020 08:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-647624" href="?#comment-647624" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570911" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="647624" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926934" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-647624"> <div class="moveup"> <div class="ttypography"><p>But would that not lead to overcounting.<br />Consider the case 3 (1 2) 4 5 and 3 1 2 (4 5).<br />These 2 permutations are same and will be counted twice, once when we consider 1,2 together and second when 4,5 are taken together.</p></div> </div> </div> <div class="reply info"> <a class="comment-647624 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-647624 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-647624"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570914" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rover1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rover1" title="Specialist rover1" class="rated-user user-cyan">rover1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570914" href="?#comment-570914" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570914" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1239447" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570914"> <div class="moveup"> <div class="ttypography"><p>If in question C, we have given a permutation of length n then we need to find happiness... Anyone want to share their approaches ..</p></div> </div> </div> <div class="reply info"> <a class="comment-570914 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570914 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570914"> <li> <div class="comment"> <table class="comment-table" commentId="570918" commentParentId="570914"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570918" href="?#comment-570918" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570914" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570918" 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-570918"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570918"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570927" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/M1v1savva1601" style="position: relative;"> <img src='https://userpic.codeforces.org/539005/avatar/21949389dc808e09.jpg'/> </a> <div><a href="/profile/M1v1savva1601" title="Master M1v1savva1601" class="rated-user user-orange">M1v1savva1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570927" href="?#comment-570927" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570927" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="539005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570927"> <div class="moveup"> <div class="ttypography"><p>Shouldn't it be <strong>eai + 1</strong> in D tutorial?</p></div> </div> </div> <div class="reply info"> <a class="comment-570927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570927"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570941" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AwakeAnay" style="position: relative;"> <img src='https://userpic.codeforces.org/666008/avatar/7043fde46ee0493c.jpg'/> </a> <div><a href="/profile/AwakeAnay" title="Grandmaster AwakeAnay" class="rated-user user-red">AwakeAnay</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 23:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570941" href="?#comment-570941" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="666008" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570941"> <div class="moveup"> <div class="ttypography"><p>I had a overkill solution for $$$D$$$ which led to a good data structures problem. While, others have provided much more elegant solutions, this reduced version is a good problem on its own and worth sharing.</p><p>Here's the problem:</p><p>You are given two sequences $$$a_i$$$ and $$$b_i$$$ of length $$$2N$$$ each. Each number from $$$1$$$ to $$$N$$$ appears exactly twice in both the sequences. You have to solve $$$Q$$$ queries of the following kind:</p><p>Given $$$l$$$, $$$r$$$, $$$x$$$ and $$$y$$$, find the set of distinct elements in $$$(l, r)$$$ in $$$a$$$ is exactly equal to the set of distinct elements in $$$(x, y)$$$ in $$$b$$$. That is, any number $$$u$$$ has an appearance in segment $$$(l, r)$$$ in $$$a$$$ if and only if it has an appearance in segment $$$(x, y)$$$ in $$$b$$$. Try to solve this online in $$$O((N+Q)\log(N))$$$.</p><p>Think of how you can reduce today's $$$D$$$ into this problem.</p><p>My code for today's D: <a href="/contest/1284/submission/68189310" title="Submission 68189310 by AwakeAnay">68189310</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570941"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570975" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/madhav_1999" style="position: relative;"> <img src='https://userpic.codeforces.org/594602/avatar/cad96e04d2a42e66.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/madhav_1999" title="Master madhav_1999" class="rated-user user-orange">madhav_1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570975" href="?#comment-570975" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570975" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="594602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570975"> <div class="moveup"> <div class="ttypography"><p>In D: &quot;Event removing interval [sbi, ebi] from S at time ebi+1.&quot;</p><p><a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a>, I think you made an error here, it should be eai + 1 instead</p></div> </div> </div> <div class="reply info"> <a class="comment-570975 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570975 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570975"> <li> <div class="comment"> <table class="comment-table" commentId="571032" commentParentId="570975"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571032" href="?#comment-571032" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570975" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571032" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571032"> <div class="moveup"> <div class="ttypography"><p>Sorry, fixed. </p></div> </div> </div> <div class="reply info"> <a class="comment-571032 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571032 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571032"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570982" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 02:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570982" href="?#comment-570982" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570982" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570982"> <div class="moveup"> <div class="ttypography"><p>Problem B can also be solved in $$$O(n)$$$. Be $$$asc$$$ the number of sequences that have an ascent. For each sequence, check if it's non-increasing. If it isn't any concatenation we do will have an ascent, so we can add $$$n$$$ to our answer and $$$1$$$ to $$$asc$$$. Now be $$$s$$$ a non-increasing sequence and let's set it as the right part of the concatenation. We will only have an ascent in the concatenation if the left part already has an ascent or has an element smaller than any element in $$$s$$$, specially it's maximum. We have $$$asc$$$ sequences of the first type, so that's easy, and for the second part we can precalculate it by creating an array $$$minfreq$$$ where we store the minimum of each non-increasing sequence in it's position (as $$$s_{i,j} &lt; 10^6$$$) and do a sweep from $$$1$$$ to $$$10^6$$$ to accumulate our sum ($$$minfreq[i] = minfreq[i-1] +minfreq[i]$$$). Now we have our answer for the second part in position $$$minfreq[max(s)-1]$$$, and we can just add both parts to our answer. Since we can precalculate $$$minfreq$$$, $$$max(s)$$$ and $$$asc$$$ in $$$O(n)$$$ and the answer can be calculated in $$$O(1)$$$ using our precalculations total complexity is $$$O(n)$$$ </p></div> </div> </div> <div class="reply info"> <a class="comment-570982 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570982 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570982"> <li> <div class="comment"> <table class="comment-table" commentId="570987" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dblark" style="position: relative;"> <img src='https://userpic.codeforces.org/693276/avatar/70323ef41e4c9add.jpg'/> </a> <div><a href="/profile/dblark" title="International Master dblark" class="rated-user user-orange">dblark</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 03:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570987" href="?#comment-570987" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570987" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="693276" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570987"> <div class="moveup"> <div class="ttypography"><p>Yeah, the same idea with you!</p></div> </div> </div> <div class="reply info"> <a class="comment-570987 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570987 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570987"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571037" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 08:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571037" href="?#comment-571037" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571037" class="CommentVoteFrame" data-commentRating="0" 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:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571037"> <div class="moveup"> <div class="ttypography"><p>I did the same, but this is not O(N). The time Complexity will be O(n + maxELE) where maxELE is the largest sequence element seen in input.</p><p>We were lucky that the constraint on that wasn't 10^9.</p><p>Also consider cases in which n = 5 but the elements are still very large, our code would still take lot of time to execute.</p></div> </div> </div> <div class="reply info"> <a class="comment-571037 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571037 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571037"> <li> <div class="comment"> <table class="comment-table" commentId="571654" commentParentId="571037"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 18:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571654" href="?#comment-571654" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571037" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571654" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571654"> <div class="moveup"> <div class="ttypography"><p>Yeah that's true, the editorial's solution is more general for that same reason</p></div> </div> </div> <div class="reply info"> <a class="comment-571654 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571654 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571654"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571551" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571551" href="?#comment-571551" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571551" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571551"> <div class="moveup"> <div class="ttypography"><p>I cant understand the minfreq[i]=minfreq[i−1]+minfreq[i] . can you explain me </p></div> </div> </div> <div class="reply info"> <a class="comment-571551 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571551 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571551"> <li> <div class="comment"> <table class="comment-table" commentId="571653" commentParentId="571551"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571653" href="?#comment-571653" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571551" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571653" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571653"> <div class="moveup"> <div class="ttypography"><p>It's called accumulated sum. Basically we want minfreq[i] to be the frequency of all numbers $$$\leq$$$ to i, so we need to push our previous array position to our current one, so that we also take into account the occurences of numbers &lt; i, and not just equal to i</p></div> </div> </div> <div class="reply info"> <a class="comment-571653 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571653 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571653"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571001" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Aguin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Aguin" title="Candidate Master Aguin" class="rated-user user-violet">Aguin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571001" href="?#comment-571001" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571001" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="297931" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571001"> <div class="moveup"> <div class="ttypography"><p>How to count different quadrilaterals in problem E?</p></div> </div> </div> <div class="reply info"> <a class="comment-571001 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571001 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571001"> <li> <div class="comment"> <table class="comment-table" commentId="571004" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571004" href="?#comment-571004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571004"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571004"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571007" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 05:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571007" href="?#comment-571007" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571007" class="CommentVoteFrame" data-commentRating="3" 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;">+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-571007"> <div class="moveup"> <div class="ttypography"><p>For example, for each pair of points $$$(i, j)$$$, we can find the number of points on one side of the line i-j ($$$a$$$), the number of points on the other side ($$$N-2-a$$$), sum that up, divide by 2 and subtract $$$2{N\choose 4}$$$. Why? For each 4-tuple of points, if one of them is inside the triangle formed by the other 3 (their convex hull is a triangle), we get 3 lines (inner point, some other point) that are counted here, and when their convex hull is a quadrilateral, we get 2 such lines — its diagonals; we subtract (2 * number of 4-tuples) to get the number of 4-tuples where one point is inside.</p><p>How to find these $$$a$$$ for each pair $$$(i, j)$$$ fast? Let's say that $$$i$$$ is fixed, sort all remaining points by their angle around point $$$i$$$, then consider a line that crosses $$$i$$$, start rotating it and whenever it crosses one of these points, update the current value of $$$a$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-571007 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571007 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571007"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571011" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571011" href="?#comment-571011" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571011" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571011"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> (<a href="/topic/73334/en9">previous revision</a>, <a href="/topic/73334/en10">new revision</a>, <a href="/topic/73334/diff/en9/en10">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-571011 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571011 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571011"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hd7" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Hd7" title="Specialist Hd7" class="rated-user user-cyan">Hd7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571018" href="?#comment-571018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571018" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="559666" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571018"> <div class="moveup"> <div class="ttypography"><p>Could anyone give me a more elaborated explanation for problem D, I didn't grasp the editorial at all.</p></div> </div> </div> <div class="reply info"> <a class="comment-571018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571031" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571031" href="?#comment-571031" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571031" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571031"> <div class="moveup"> <div class="ttypography"><p>Expected a matroid problem, as <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> took matroid class last semester XD</p></div> </div> </div> <div class="reply info"> <a class="comment-571031 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571031 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571031"> <li> <div class="comment"> <table class="comment-table" commentId="571033" commentParentId="571031"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571033" href="?#comment-571033" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571031" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571033" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571033"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/team/65651">matroid fan club!</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571033 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571033 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571033"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571040" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PouyaNavid" style="position: relative;"> <img src='https://userpic.codeforces.org/670316/avatar/c42e949ea38011da.jpg'/> </a> <div><a href="/profile/PouyaNavid" title="Master PouyaNavid" class="rated-user user-orange">PouyaNavid</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 09:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571040" href="?#comment-571040" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571040" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="670316" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571040"> <div class="moveup"> <div class="ttypography"><p>Hack Test for D <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a></p><p>4 1 10 51 60 2 20 44 52 3 40 43 45 42 45 50 50</p></div> </div> </div> <div class="reply info"> <a class="comment-571040 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571040 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571040"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571088" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hazyknight" style="position: relative;"> <img src='https://userpic.codeforces.org/537474/avatar/e2c88ee4c2562699.jpg'/> </a> <div><a href="/profile/Hazyknight" title="International Grandmaster Hazyknight" class="rated-user user-red">Hazyknight</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571088" href="?#comment-571088" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571088" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571088" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="537474" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571088"> <div class="moveup"> <div class="ttypography"><p>Actually, Problem G can be solved easily by matroid intersection. Consider two matroid M1(S,I),M2(S,I), S is the set of wall, M1 is a graph matroid , M2 is a matroid which any black cell has at least to side without wall. Code: <a href="https://codeforces.com/contest/1284/submission/68215804">https://codeforces.com/contest/1284/submission/68215804</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571088 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571088 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571088"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571128" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amstan" style="position: relative;"> <img src='https://userpic.codeforces.org/734003/avatar/344c500da9a98a7f.jpg'/> </a> <div><a href="/profile/amstan" title="Expert amstan" class="rated-user user-blue">amstan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571128" href="?#comment-571128" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571128" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="734003" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571128"> <div class="moveup"> <div class="ttypography"><p>Is there anyone who solved D using coordinate compression and prefix sum ? If so, could you please share your submission.</p></div> </div> </div> <div class="reply info"> <a class="comment-571128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571128"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571138" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HaoxuanXIE" style="position: relative;"> <img src='https://userpic.codeforces.org/1234114/avatar/fa4b56dfead7992e.jpg'/> </a> <div><a href="/profile/HaoxuanXIE" title="Expert HaoxuanXIE" class="rated-user user-blue">HaoxuanXIE</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571138" href="?#comment-571138" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571138" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1234114" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571138"> <div class="moveup"> <div class="ttypography"><p>Why does D need to check in two directions? If I check in one direction, I get wrong answer at 9th point. But I think it is appropriate to check in only one direction.</p></div> </div> </div> <div class="reply info"> <a class="comment-571138 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571138 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571138"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571145" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheeLooser" style="position: relative;"> <img src='https://userpic.codeforces.org/448032/avatar/d5dcfa8c5dbd255f.jpg'/> </a> <div><a href="/profile/TheeLooser" title="Expert TheeLooser" class="rated-user user-blue">TheeLooser</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571145" href="?#comment-571145" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571145" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="448032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571145"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> may as well check how many visits were made to <a href="https://codeforces.com/problemset/problem/1146/H">this</a> page and later to <a href="https://codeforces.com/blog/entry/66639">this</a> page in contest time</p></div> </div> </div> <div class="reply info"> <a class="comment-571145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571145"> <li> <div class="comment"> <table class="comment-table" commentId="571459" commentParentId="571145"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 22:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571459" href="?#comment-571459" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571145" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571459" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571459"> <div class="moveup"> <div class="ttypography"><p>How does that problem help?</p></div> </div> </div> <div class="reply info"> <a class="comment-571459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571459"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571509" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Petr" style="position: relative;"> <img src='https://userpic.codeforces.org/664/avatar/a113c1791cdcd2e1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Petr" title="Legendary Grandmaster Petr" class="rated-user user-legendary"><span class="legendary-user-first-letter">P</span>etr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 01:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571509" href="?#comment-571509" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571509" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="664" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571509"> <div class="moveup"> <div class="ttypography"><p>Re: &quot;Hopefully, the first 80 tests were good enough for the contest.&quot;</p><p>My <a href="https://codeforces.com/contest/1284/submission/68208450">random solution</a> fails on test 87 :) Great job making the tests indeed!</p></div> </div> </div> <div class="reply info"> <a class="comment-571509 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571509 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571509"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571522" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MubtasimShahriar" style="position: relative;"> <img src='https://userpic.codeforces.org/756984/avatar/9113baa4abf04299.jpg'/> </a> <div><a href="/profile/MubtasimShahriar" title="Pupil MubtasimShahriar" class="rated-user user-green">MubtasimShahriar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 05:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571522" href="?#comment-571522" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571522" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756984" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571522"> <div class="moveup"> <div class="ttypography"><p>In Problem D, why does this solution not work? My Solutions is this.</p><p>Sort lectures according to their start-ending time in both venue, Then decide every lecture if it intersects with others in their own venue.</p><p>If there is at least one lecture that make difference in intersecting in both venue, then Subset can not be made. So the answer is no. If every problem either intersects in both venue or does not intersect in both venue then answer is yes. Here is my implementation <a href="/contest/1284/submission/68294866" title="Submission 68294866 by MubtasimShahriar">68294866</a></p><p>Please someone enlighten me where I am misunderstanding.</p></div> </div> </div> <div class="reply info"> <a class="comment-571522 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571522 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571522"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571546" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SLIMSHADYNICK" style="position: relative;"> <img src='https://userpic.codeforces.org/598862/avatar/7629f1b29f0fe807.jpg'/> </a> <div><a href="/profile/SLIMSHADYNICK" title="Candidate Master SLIMSHADYNICK" class="rated-user user-violet">SLIMSHADYNICK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571546" href="?#comment-571546" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571546" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-13" data-commentUserId="598862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-571546"> <div class="moveup"> <div class="ttypography"><p>In problem D, I got wrong answer on test case 14. Can somebody please help.</p></div> </div> </div> <div class="reply info"> <a class="comment-571546 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571546 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571546"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572491" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ftiasch" style="position: relative;"> <img src='https://userpic.codeforces.org/506/avatar/c52be21fbeb4a450.jpg'/> </a> <div><a href="/profile/ftiasch" title="International Grandmaster ftiasch" class="rated-user user-red">ftiasch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/11/2020 00:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572491" href="?#comment-572491" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572491" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="506" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-572491"> <div class="moveup"> <div class="ttypography"><p>2020 begins with two matroid problems. XD</p><p>btw, Challenge in Problem F is called Strong Basis Exchange as in <a href="https://math.mit.edu/~goemans/18438F09/lec11.pdf">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-572491 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572491 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572491"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572780" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Akash79" style="position: relative;"> <img src='https://userpic.codeforces.org/776725/avatar/700a28ac96121584.jpg'/> </a> <div><a href="/profile/Akash79" title="Expert Akash79" class="rated-user user-blue">Akash79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 16:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572780" href="?#comment-572780" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572780" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="776725" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572780"> <div class="moveup"> <div class="ttypography"><p>I am not able to understand problem B's solution.. can anyone please help me out..??</p></div> </div> </div> <div class="reply info"> <a class="comment-572780 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572780 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572780"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 17:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572849" href="?#comment-572849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="572849" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="572849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572849"> <div class="moveup"> <div class="ttypography"><p>Why don't we have to consider the case when there's some period intersecting in A and not intersecting in B? Doesn't that mean that sometimes our code will say 'YES' but the answer is 'NO'. Why? <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a>. EDIT: Ok, I just didn't notice the part of the code where he does the same thing but reversed.</p></div> </div> </div> <div class="reply info"> <a class="comment-572849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572849"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572863" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 18:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572863" href="?#comment-572863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572863" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572863"> <div class="moveup"> <div class="ttypography"><p>What is the hash approach for the problem D?</p></div> </div> </div> <div class="reply info"> <a class="comment-572863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572863"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="576477" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anaksoleh" style="position: relative;"> <img src='https://userpic.codeforces.org/1170460/avatar/27d790d7abbbd3d9.jpg'/> </a> <div><a href="/profile/anaksoleh" title="Newbie anaksoleh" class="rated-user user-gray">anaksoleh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/30/2020 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576477" href="?#comment-576477" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576477" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170460" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-576477"> <div class="moveup"> <div class="ttypography"><p>there is a proof for C solution ?</p></div> </div> </div> <div class="reply info"> <a class="comment-576477 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576477 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576477"> <li> <div class="comment"> <table class="comment-table" commentId="673042" commentParentId="576477"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/XORring-Samurai" style="position: relative;"> <img src='https://userpic.codeforces.org/1384228/avatar/d0258d5ed6604923.jpg'/> </a> <div><a href="/profile/XORring-Samurai" title="Candidate Master XORring-Samurai" class="rated-user user-violet">XORring-Samurai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/02/2020 09:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-673042" href="?#comment-673042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-576477" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="673042" 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="673042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1384228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-673042"> <div class="moveup"> <div class="ttypography"><p>Here is something, that I could think of.</p><p>For each permutation, we have the same $$$r-l$$$. This value varies from $$$0$$$ to $$$n-1$$$ for all $$$n$$$. Now let us consider $$$r-l=d$$$, as a general case. </p><p>For each $$$n$$$, we have $$$n-d$$$ pairs of $$$[l, r]$$$, where $$$r-l=d$$$. Also for all numbers from $$$1$$$ to $$$n$$$, we have $$$n-d$$$ pairs of type $$$[i, j]$$$ such that $$$j-i=d$$$. </p><p>For a segment to be framed, all the other places for each $$$[l, r]$$$ must be occupied by each integer from $$$[i, j]$$$. Therefore, we have $$$d+1$$$ numbers to be arranged in this interval $$$[l, r]$$$ and $$$n-d-1$$$ to be arranged in $$$[1, l-1]$$$ and $$$[r+1, n]$$$. This can be done in $$$(d+1)! * (n-d-1)!$$$ ways. </p><p>But we have $$$n-d$$$ pairs of $$$[l, r]$$$ and $$$n-d$$$ pairs of $$$[i, j]$$$, each of which can occupy this segment. Therefore the answer becomes summation over all $$$d$$$ from $$$0$$$ to $$$n-1$$$: $$$ans = ans + (n-d) * (n-d) * (d+1)! * (n-d-1)!$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-673042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-673042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-673042"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606852" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ThakurSaab" style="position: relative;"> <img src='https://userpic.codeforces.org/1267713/avatar/7c6c4d7b58cddb96.jpg'/> </a> <div><a href="/profile/ThakurSaab" title="Expert ThakurSaab" class="rated-user user-blue">ThakurSaab</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 17:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606852" href="?#comment-606852" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606852" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1267713" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606852"> <div class="moveup"> <div class="ttypography"><p>In problem C , do we consider that the numbers inside a particular segment [l,r] could be different such that, max-min = r-l</p></div> </div> </div> <div class="reply info"> <a class="comment-606852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606852"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="689589" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 07:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689589" href="?#comment-689589" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689589" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689589"> <div class="moveup"> <div class="ttypography"><p>In Problem D I added elements in the segment tree in the decreasing order of eai and then I queried for the previous range if the min of the ls and the maxr intersect with the particular index of a I am addding . I am getting a WA at Test Case 7 for this submission.</p><p>This is my submission link: <a href="https://codeforces.com/contest/1284/submission/91535000">https://codeforces.com/contest/1284/submission/91535000</a></p><p>Can somebody help me with this solution where I went wrong? </p><p>Or is there anyway I can look at the whole testcase then please reply here about how can I do that?</p></div> </div> </div> <div class="reply info"> <a class="comment-689589 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689589 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689589"> <li> <div class="comment"> <table class="comment-table" commentId="689595" commentParentId="689589"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 08:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689595" href="?#comment-689595" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-689589" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689595" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689595"> <div class="moveup"> <div class="ttypography"><p>Never Mind I made a silly typo in the cmp2 function.</p></div> </div> </div> <div class="reply info"> <a class="comment-689595 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689595 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689595"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="722358" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tanishq_code_c" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tanishq_code_c" title="Expert tanishq_code_c" class="rated-user user-blue">tanishq_code_c</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/17/2020 17:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-722358" href="?#comment-722358" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="722358" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1484322" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-722358"> <div class="moveup"> <div class="ttypography"><p>Hi, I am not able to understand the editorial for problem C. can anyone break it down in easy way please ? </p></div> </div> </div> <div class="reply info"> <a class="comment-722358 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-722358 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-722358"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="736312" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheOneYouWant" style="position: relative;"> <img src='https://userpic.codeforces.org/628619/avatar/c785428bde285c3.jpg'/> </a> <div><a href="/profile/TheOneYouWant" title="Master TheOneYouWant" class="rated-user user-orange">TheOneYouWant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/23/2020 05:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-736312" href="?#comment-736312" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="736312" class="CommentVoteFrame" data-commentRating="91" data-commentUserId="628619" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+91</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-736312"> <div class="moveup"> <div class="ttypography"><p>Hello, this seems to be broken (perhaps a sign of how the year 2020 has been so far)</p></div> </div> </div> <div class="reply info"> <a class="comment-736312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-736312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-736312"> <li> <div class="comment"> <table class="comment-table" commentId="737407" commentParentId="736312"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/27/2020 09:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-737407" href="?#comment-737407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-736312" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="737407" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-737407"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> please take a look, thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-737407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-737407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-737407"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741444" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/butterflies" style="position: relative;"> <img src='https://userpic.codeforces.org/1651561/avatar/33dfc9c16e5795ad.jpg'/> </a> <div><a href="/profile/butterflies" title="Specialist butterflies" class="rated-user user-cyan">butterflies</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741444" href="?#comment-741444" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="741444" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="741444" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1651561" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741444"> <div class="moveup"> <div class="ttypography"><p>This question relates to <a href="https://codeforces.com/contest/1284/problem/B">problem B</a>. I have a question with the second example input. Here is the input:</p> <pre><code>3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 </code></pre><p>I believe all arrays have an ascent. In the first array, the pair $$$(i, j) = (3, 4)$$$ works. ($$$a_3 = 0, a_4 = 2.$$$) In the second array, the pair $$$(i, j) = (1, 2)$$$ works. ($$$a_1 = 6, a_2 = 9.$$$) In the third array, the pair $$$(i,j) = (1, 2)$$$ works. ($$$a_1 = 1, a_2 = 6.$$$)</p><p>Thus, shouldn't all pairs of arrays in this case work? There are $$$9$$$ such pairs, but the answer to this should be $$$7.$$$ What is wrong with my reasoning here?</p></div> </div> </div> <div class="reply info"> <a class="comment-741444 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741444 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741444"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741445" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/beetroot" style="position: relative;"> <img src='https://userpic.codeforces.org/1503072/avatar/6668dbf5be4e4495.jpg'/> </a> <div><a href="/profile/beetroot" title="Expert beetroot" class="rated-user user-blue">beetroot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741445" href="?#comment-741445" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741445" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1503072" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741445"> <div class="moveup"> <div class="ttypography"><p>Editorials that didn't age well...</p></div> </div> </div> <div class="reply info"> <a class="comment-741445 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741445 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741445"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741475" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 07:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741475" href="?#comment-741475" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741475" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741475"> <div class="moveup"> <div class="ttypography"><p>Sorry for the issue with editorials. I think there is a timeout issue from Polygon. Since I can't resolve it, I will just rewrite it as a PDF form and upload here.</p></div> </div> </div> <div class="reply info"> <a class="comment-741475 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741475 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741475"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="797067" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/YPK" style="position: relative;"> <img src='https://userpic.codeforces.org/1489397/avatar/bd42de2aca7084dd.jpg'/> </a> <div><a href="/profile/YPK" title="Master YPK" class="rated-user user-orange">YPK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/29/2021 11:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-797067" href="?#comment-797067" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="797067" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="797067" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1489397" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-797067"> <div class="moveup"> <div class="ttypography"><p>Weak test cases for D. Consider the following test case </p> <pre><code>3 1 3 1 2 4 6 4 5 5 7 2 3 </code></pre><p>My accepted solution gives YES but the answer is NO.</p></div> </div> </div> <div class="reply info"> <a class="comment-797067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-797067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-797067"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="891199" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav04" style="position: relative;"> <img src='https://userpic.codeforces.org/2093148/avatar/b05253879beed26d.jpg'/> </a> <div><a href="/profile/abhinav04" title="Specialist abhinav04" class="rated-user user-cyan">abhinav04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/27/2022 11:56">19 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-891199" href="?#comment-891199" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="891199" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="2093148" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-891199"> <div class="moveup"> <div class="ttypography"><p>In case someone needs help with problem B, this might help.</p> <div class="spoiler"><b class="spoiler-title">submission</b><div class="spoiler-content" style="display: none;"><p><a href="https://codeforces.com/contest/1284/submission/147841447">https://codeforces.com/contest/1284/submission/147841447</a></p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-891199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-891199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-891199"> </ul> </div> <br/> <div id="editBox-78289" 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 firstPreview78289 = true; var lastPreviewContent78289 = ''; 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=78289] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=78289] 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-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, 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:27:29</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81288aad58e60057',t:'MTY5NjcwNjg0OS42NzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1284G
1284
G
ru
G. Корейский Новый год
<div class="problem-statement"><div class="header"><div class="title">G. Корейский Новый год</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Осталось несколько дней до Корейского Нового года, и Джаехьюн пригласил свою семью в сад. Среди гостей есть дети. Чтобы сделать времяпровождение для них интереснее, Джаехьюн решил устроить игру в прятки.</p><p>Сад можно описать как таблицу $$$n \times m$$$ из единичных клеток. Некоторые (возможно ноль) из них заняты камнями, а остальные свободны. Две клетки называются соседними если у них есть общее ребро. Таким образом, у каждой клетки есть не более четырех соседей: два по горизонтали, и два по вертикали.</p><p>Так как сад можно описать как таблицу, клетки бывают двух видов: «<span class="tex-font-style-tt">черные</span>» или «<span class="tex-font-style-tt">белые</span>», как в шахматной доске. Первая клетка $$$(1, 1)$$$ черная. А затем, остальные клетки покрашены чередуясь. Клетки пронумерованы в 1-индексации.</p><p>Джаехьюн хочет превратить его сад в <span class="tex-font-style-it">лабиринт</span> расстановкой стен между двумя клетками. Стены могут быть размещены только между соседними клетками. Если поставить стену между двумя соседними клетками $$$a$$$ и $$$b$$$, тогда клетки $$$a$$$ и $$$b$$$ больше не считаются соседними. Можно идти прямо между двумя соседними клетками тогда и только тогда, когда нет прямой стены между ними.</p><p><span class="tex-font-style-it">Лабиринт</span> должен обладать следующим свойством. Для каждой пары свободных клеток, должен быть ровно один простой путь между ними. Простой путь между клетками $$$a$$$ и $$$b$$$ это последовательность клеток, в которой первая клетка $$$a$$$, последняя $$$b$$$, все клетки различны, и любые две подряд идущие клетки являются соседями, между которыми не стоит стена.</p><p>Сначала, дети соберутся в клетке $$$(1, 1)$$$, и начнут играть в прятки. Ребенок может спрятаться в клетке если и только если это не стартовая клетка $$$(1, 1)$$$, и у нее есть ровно один свободный сосед. Джаехьюн посадил розы в черных клетках, так что там опасно прятаться. Поэтому Джаехьюн хочет построить лабиринт, в котором дети смогут прятаться только в клетках белого цвета.</p><p>Вам дана карта сада. Ваша задача — помочь Джаехьюну построить лабиринт.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Вашей программе нужно будет обработать несколько тестовых случаев.</p><p>В первой строке записано количество тестовых случаев $$$t$$$ ($$$1 \le t \le 100$$$). Затем, $$$t$$$ тестовых случаев даны в описанном далее формате: </p><p>Первая строка тестового случая содержит два целых числа $$$n, m$$$, размеры таблицы ($$$2 \le n, m \le 20$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит строку длины $$$m$$$, состоящую из следующих символов (без пробелов): </p><ul> <li> <span class="tex-font-style-tt">O</span>: Пустая клетка. </li><li> <span class="tex-font-style-tt">X</span>: Камень. </li></ul><p>Гарантируется, что первая клетка (клетка $$$(1, 1)$$$) свободная, и все свободные клетки достижимы из $$$(1, 1)$$$. </p><p><span class="tex-font-style-bf">Если $$$t \geq 2$$$, то в каждом тестовом случае размеры поля удовлетворяют $$$n \le 10, m \le 10$$$</span>. Иначе говоря, если во вводе дана таблица с $$$n &gt; 10$$$ или $$$m &gt; 10$$$, то это будет единственный тестовой случай во вводе ($$$t = 1$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите следующее:</p><p>Если нет возможных лабиринтов, выведите <span class="tex-font-style-tt">NO</span>.</p><p>Иначе, выведите <span class="tex-font-style-tt">YES</span>, после чего выведите таблицу $$$(2n-1) \times (2m-1)$$$ описывающих выбранный лабиринт. Все клетки в 1-индексации. Правила описания лабиринта следующие:</p><ul> <li> Для всех $$$1 \le i \le n, 1 \le j \le m$$$, если клетка $$$(i, j)$$$ свободная, выведите <span class="tex-font-style-tt">'O'</span> в клетке $$$(2i-1, 2j-1)$$$. Иначе, выедите <span class="tex-font-style-tt">'X'</span> в клетке $$$(2i-1, 2j-1)$$$. </li><li> Для всех $$$1 \le i \le n, 1 \le j \le m-1$$$, если между клетками $$$(i, j), (i, j+1)$$$ стоит стена, выведите <span class="tex-font-style-tt">' '</span> в клетке $$$(2i-1, 2j)$$$. Иначе, выведите <span class="tex-font-style-bf">любой выводимый символ кроме пробела</span> в клетке $$$(2i-1, 2j)$$$. У выводимого символа ASCII код расположен в отрезке $$$[32, 126]$$$: Это включает пробелы, буквы, и цифры. </li><li> Для всех $$$1 \le i \le n-1, 1 \le j \le m$$$, если между клетками $$$(i, j), (i+1, j)$$$ стоит стена, выведите <span class="tex-font-style-tt">' '</span> в клетке $$$(2i, 2j-1)$$$. Иначе, выведите <span class="tex-font-style-bf">любой выводимый символ кроме пробела</span> в клетке $$$(2i, 2j-1)$$$. </li><li> Для всех $$$1 \le i \le n-1, 1 \le j \le m-1$$$, выведите <span class="tex-font-style-bf">любой выводимый символ</span> в клетке $$$(2i, 2j)$$$. </li></ul><p>Пожалуйста, будьте аккуратны с лишними символами переноса строк и пробелами. Каждая строка таблицы должна содержать <span class="tex-font-style-bf">ровно $$$2m-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 2 2 OO OO 3 3 OOO XOO OOO 4 4 OOOX XOOX OOXO OOOO 5 6 OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES OOO O OOO NO YES OOOOO X O O X O O X O OOO X O O O O O OOOOO YES OOOOOOOOOOO O O O OOO OOO OOO O O O OOO OOO OOO O O O OOO OOO OOO O O O OOO OOO OOO </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="bce7c76adb9f8e21c5ee5cbc4df513dd"/> <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="844107ee75ef6ee8a5d433a0bcfbbda150cb7f74"/> <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='bce7c76adb9f8e21c5ee5cbc4df513dd'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1284%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='bce7c76adb9f8e21c5ee5cbc4df513dd'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1284">Hello 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='bce7c76adb9f8e21c5ee5cbc4df513dd'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1284/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound 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='bce7c76adb9f8e21c5ee5cbc4df513dd'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="508368"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bce7c76adb9f8e21c5ee5cbc4df513dd'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="508368"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72725" title="Hello 2020" target="_blank">Hello 2020 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10228" resourceName="Hello 2020" resourceManual="true" src="//codeforces.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/72804" title="Hello 2020 Editorial" target="_blank">Hello 2020 Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10239" resourceName="Hello 2020 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/1284">Задачи</a></li> <li><a href="/contest/1284/submit">Отослать</a></li> <li><a href="/contest/1284/my">Мои посылки</a></li> <li><a href="/contest/1284/status">Статус</a></li> <li><a href="/contest/1284/hacks">Взломы</a></li> <li><a href="/contest/1284/room/1">Комната</a></li> <li><a href="/contest/1284/standings">Положение</a></li> <li><a href="/contest/1284/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_76c6c0fbb272cc742c29f522a846ad39c786c0f4"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">G. Корейский Новый год</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Осталось несколько дней до Корейского Нового года, и Джаехьюн пригласил свою семью в сад. Среди гостей есть дети. Чтобы сделать времяпровождение для них интереснее, Джаехьюн решил устроить игру в прятки.</p><p>Сад можно описать как таблицу $$$n \times m$$$ из единичных клеток. Некоторые (возможно ноль) из них заняты камнями, а остальные свободны. Две клетки называются соседними если у них есть общее ребро. Таким образом, у каждой клетки есть не более четырех соседей: два по горизонтали, и два по вертикали.</p><p>Так как сад можно описать как таблицу, клетки бывают двух видов: «<span class="tex-font-style-tt">черные</span>» или «<span class="tex-font-style-tt">белые</span>», как в шахматной доске. Первая клетка $$$(1, 1)$$$ черная. А затем, остальные клетки покрашены чередуясь. Клетки пронумерованы в 1-индексации.</p><p>Джаехьюн хочет превратить его сад в <span class="tex-font-style-it">лабиринт</span> расстановкой стен между двумя клетками. Стены могут быть размещены только между соседними клетками. Если поставить стену между двумя соседними клетками $$$a$$$ и $$$b$$$, тогда клетки $$$a$$$ и $$$b$$$ больше не считаются соседними. Можно идти прямо между двумя соседними клетками тогда и только тогда, когда нет прямой стены между ними.</p><p><span class="tex-font-style-it">Лабиринт</span> должен обладать следующим свойством. Для каждой пары свободных клеток, должен быть ровно один простой путь между ними. Простой путь между клетками $$$a$$$ и $$$b$$$ это последовательность клеток, в которой первая клетка $$$a$$$, последняя $$$b$$$, все клетки различны, и любые две подряд идущие клетки являются соседями, между которыми не стоит стена.</p><p>Сначала, дети соберутся в клетке $$$(1, 1)$$$, и начнут играть в прятки. Ребенок может спрятаться в клетке если и только если это не стартовая клетка $$$(1, 1)$$$, и у нее есть ровно один свободный сосед. Джаехьюн посадил розы в черных клетках, так что там опасно прятаться. Поэтому Джаехьюн хочет построить лабиринт, в котором дети смогут прятаться только в клетках белого цвета.</p><p>Вам дана карта сада. Ваша задача — помочь Джаехьюну построить лабиринт.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Вашей программе нужно будет обработать несколько тестовых случаев.</p><p>В первой строке записано количество тестовых случаев $$$t$$$ ($$$1 \le t \le 100$$$). Затем, $$$t$$$ тестовых случаев даны в описанном далее формате: </p><p>Первая строка тестового случая содержит два целых числа $$$n, m$$$, размеры таблицы ($$$2 \le n, m \le 20$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит строку длины $$$m$$$, состоящую из следующих символов (без пробелов): </p><ul> <li> <span class="tex-font-style-tt">O</span>: Пустая клетка. </li><li> <span class="tex-font-style-tt">X</span>: Камень. </li></ul><p>Гарантируется, что первая клетка (клетка $$$(1, 1)$$$) свободная, и все свободные клетки достижимы из $$$(1, 1)$$$. </p><p><span class="tex-font-style-bf">Если $$$t \geq 2$$$, то в каждом тестовом случае размеры поля удовлетворяют $$$n \le 10, m \le 10$$$</span>. Иначе говоря, если во вводе дана таблица с $$$n &gt; 10$$$ или $$$m &gt; 10$$$, то это будет единственный тестовой случай во вводе ($$$t = 1$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите следующее:</p><p>Если нет возможных лабиринтов, выведите <span class="tex-font-style-tt">NO</span>.</p><p>Иначе, выведите <span class="tex-font-style-tt">YES</span>, после чего выведите таблицу $$$(2n-1) \times (2m-1)$$$ описывающих выбранный лабиринт. Все клетки в 1-индексации. Правила описания лабиринта следующие:</p><ul> <li> Для всех $$$1 \le i \le n, 1 \le j \le m$$$, если клетка $$$(i, j)$$$ свободная, выведите <span class="tex-font-style-tt">'O'</span> в клетке $$$(2i-1, 2j-1)$$$. Иначе, выедите <span class="tex-font-style-tt">'X'</span> в клетке $$$(2i-1, 2j-1)$$$. </li><li> Для всех $$$1 \le i \le n, 1 \le j \le m-1$$$, если между клетками $$$(i, j), (i, j+1)$$$ стоит стена, выведите <span class="tex-font-style-tt">' '</span> в клетке $$$(2i-1, 2j)$$$. Иначе, выведите <span class="tex-font-style-bf">любой выводимый символ кроме пробела</span> в клетке $$$(2i-1, 2j)$$$. У выводимого символа ASCII код расположен в отрезке $$$[32, 126]$$$: Это включает пробелы, буквы, и цифры. </li><li> Для всех $$$1 \le i \le n-1, 1 \le j \le m$$$, если между клетками $$$(i, j), (i+1, j)$$$ стоит стена, выведите <span class="tex-font-style-tt">' '</span> в клетке $$$(2i, 2j-1)$$$. Иначе, выведите <span class="tex-font-style-bf">любой выводимый символ кроме пробела</span> в клетке $$$(2i, 2j-1)$$$. </li><li> Для всех $$$1 \le i \le n-1, 1 \le j \le m-1$$$, выведите <span class="tex-font-style-bf">любой выводимый символ</span> в клетке $$$(2i, 2j)$$$. </li></ul><p>Пожалуйста, будьте аккуратны с лишними символами переноса строк и пробелами. Каждая строка таблицы должна содержать <span class="tex-font-style-bf">ровно $$$2m-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 2 2 OO OO 3 3 OOO XOO OOO 4 4 OOOX XOOX OOXO OOOO 5 6 OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES OOO O OOO NO YES OOOOO X O O X O O X O OOO X O O O O O OOOOO YES OOOOOOOOOOO O O O OOO OOO OOO O O O OOO OOO OOO O O O OOO OOO OOO O O O OOO OOO OOO </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:54: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:'812493311b1816b3',t:'MTY5NjY2NTI1NC42OTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*3300"]
https://codeforces.com/blog/entry/72804
<!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="17bb3c0a988bbcfabcfbab3b80b286ce"/> <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="Hello 2020 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>Hello 2020 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='17bb3c0a988bbcfabcfbab3b80b286ce'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F72804">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='17bb3c0a988bbcfabcfbab3b80b286ce'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:37:33</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:37:33</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div><div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='17bb3c0a988bbcfabcfbab3b80b286ce'/> <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/ko_osaga">ko_osaga</a></li> <li class="current selectedLava"><a href="/blog/ko_osaga">Blog</a></li> <li><a href="/teams/with/ko_osaga">Teams</a></li> <li><a href="/submissions/ko_osaga">Submissions</a></li> <li><a href="/groups/with/ko_osaga">Groups</a></li> <li><a href="/contests/with/ko_osaga">Contests</a></li> <li><a href="/contests/writer/ko_osaga">Problemsetting</a></li> <li><a href="/streams/ko_osaga">Streams</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ko_osaga" style="text-decoration:none;color:black !important;">ko_osaga's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="73334"> <div class="title"> <a href="/blog/entry/72804"> <p>Hello 2020 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a>, <a href="/topic/73334/en12">history</a>, <span class="format-humantime" title="Jan/04/2020 18:44">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>Since the Polygon tutorial system is currently broken, I will replace the editorial with PDF format. Sorry for the inconvenience!</p><p><a href="https://www.dropbox.com/s/ysttw748rvx46eb/Hello%202020.pdf?dl=0">Solution PDF</a></p><p>Problem A was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203276">Code</a></p><p>Problem B was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203332">Code</a></p><p>Problem C was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203721">Code</a></p><p>Problem D was authored by <a class="rated-user user-orange" href="/profile/nong" title="Master nong">nong</a>. <a href="https://codeforces.com/contest/1284/submission/68203704">Code</a></p><p>Problem E was authored by <a class="rated-user user-orange" href="/profile/ckw1140" title="Master ckw1140">ckw1140</a>. <a href="https://codeforces.com/contest/1284/submission/68203754">Code</a></p><p>Problem F was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203787">Code</a></p><p>Problem G was authored by <a class="rated-user user-legendary" href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga"><span class="legendary-user-first-letter">k</span>o_osaga</a>. <a href="https://codeforces.com/contest/1284/submission/68203817">Code</a></p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1284" class="notice" style="text-decoration: none;">Hello 2020</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-38652-73334").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "38652", blogEntryId: "72804", 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-73334"><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'>+191</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-73334"><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/ko_osaga"><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/ko_osaga"> ko_osaga </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="Jan/04/2020 18:44">4 years ago</span> </li> <li> <a href="/blog/entry/72804#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/72804#comments"> 157 </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="78289"> <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 (143)</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="570690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SHZhang" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SHZhang" title="International Grandmaster SHZhang" class="rated-user user-red">SHZhang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570690" href="?#comment-570690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570690" class="CommentVoteFrame" data-commentRating="50" data-commentUserId="1150683" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+50</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570690"> <div class="moveup"> <div class="ttypography"><p>When I open the editorial for problem E, I see the editorial for problem C instead. Can the author fix this, please?</p></div> </div> </div> <div class="reply info"> <a class="comment-570690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570690"> <li> <div class="comment"> <table class="comment-table" commentId="570700" commentParentId="570690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570700" href="?#comment-570700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570700" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570700"> <div class="moveup"> <div class="ttypography"><p>Sorry, it's fixed now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570700"> <li> <div class="comment"> <table class="comment-table" commentId="598782" commentParentId="570700"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jokerwyt" style="position: relative;"> <img src='https://userpic.codeforces.org/555567/avatar/247d0346874bdbdd.jpg'/> </a> <div><a href="/profile/jokerwyt" title="Candidate Master jokerwyt" class="rated-user user-violet">jokerwyt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/07/2020 16:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-598782" href="?#comment-598782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570700" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="598782" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555567" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-598782"> <div class="moveup"> <div class="ttypography"><p>Challenge of problem E is nice, but i have no idea how to solve it. Could you provide the solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-598782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-598782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-598782"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/21August" style="position: relative;"> <img src='https://userpic.codeforces.org/452773/avatar/13e016fa74fb3308.jpg'/> </a> <div><a href="/profile/21August" title="Master 21August" class="rated-user user-orange">21August</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570691" href="?#comment-570691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570691" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="452773" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570691"> <div class="moveup"> <div class="ttypography"><p>You got it wrong for E.</p></div> </div> </div> <div class="reply info"> <a class="comment-570691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570691"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570695" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 18:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570695" href="?#comment-570695" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570695" 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-570695"> <div class="moveup"> <div class="ttypography"><p>Really liked problems B and C :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570695"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570706" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TimonKnigge" style="position: relative;"> <img src='https://userpic.codeforces.org/275246/avatar/debe81b88ed671c2.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/TimonKnigge" title="Master TimonKnigge" class="rated-user user-orange">TimonKnigge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570706" href="?#comment-570706" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570706" class="CommentVoteFrame" data-commentRating="86" data-commentUserId="275246" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+86</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570706"> <div class="moveup"> <div class="ttypography"><p>Problem D is a lot more intuitive if you interpret the input as a collection of rectangles, where you are asked if there is a pair of rectangles that overlaps on one axis but not the other. Then a scanline solution is obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-570706 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570706 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570706"> <li> <div class="comment"> <table class="comment-table" commentId="570804" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Skeef79" style="position: relative;"> <img src='https://userpic.codeforces.org/631759/avatar/3033511aaec49179.jpg'/> </a> <div><a href="/profile/Skeef79" title="Candidate Master Skeef79" class="rated-user user-violet">Skeef79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570804" href="?#comment-570804" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570804"> <div class="moveup"> <div class="ttypography"><p>Can you please give some good resources about scanline? </p></div> </div> </div> <div class="reply info"> <a class="comment-570804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570804"> <li> <div class="comment"> <table class="comment-table" commentId="570996" commentParentId="570804"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rezwan.Arefin01" style="position: relative;"> <img src='https://userpic.codeforces.org/358701/avatar/68ec3668b1ccc552.jpg'/> </a> <div><a href="/profile/Rezwan.Arefin01" title="Candidate Master Rezwan.Arefin01" class="rated-user user-violet">Rezwan.Arefin01</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570996" href="?#comment-570996" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570804" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570996" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="358701" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570996"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.topcoder.com/community/competitive-programming/tutorials/line-sweep-algorithms/">Topcoder Tutorials</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570996 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570996 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570996"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570807" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570807" href="?#comment-570807" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570807" class="CommentVoteFrame" data-commentRating="33" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+33</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570807"> <div class="moveup"> <div class="ttypography"><p>That was the original formulation. I came up with the conference statement to make this problem much natural ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-570807 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570807 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570807"> <li> <div class="comment"> <table class="comment-table" commentId="571201" commentParentId="570807"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ghoshsai5000" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ghoshsai5000" title="Pupil ghoshsai5000" class="rated-user user-green">ghoshsai5000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571201" href="?#comment-571201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570807" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571201" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="543439" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571201"> <div class="moveup"> <div class="ttypography"><p>This was eye-opening ! So, the input format is $$$x_1, x_2, y_1, y_2$$$ and we have to look for $$$2$$$ rectangles such that their $$$x$$$-axes coincide but their $$$y$$$ do not or the other way around. </p><p>First time, we sort by $$$x$$$ and for every new line segment we process, we keep track of all the line segments it inserts with. We will check if the corresponding $$$y$$$ of the line segment fits in the bounds of all the line segments it has intersected so far. </p> <ul> <li>$$$y_1$$$ should not be greater than the smallest $$$y_2$$$ seen so far.</li> <li>$$$y_2$$$ should not be lesser than the greatest $$$y_1$$$ seen so far.</li> </ul><p>If you could include this interpretation in the editorial, it would help in understanding a lot :)</p></div> </div> </div> <div class="reply info"> <a class="comment-571201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571201"> <li> <div class="comment"> <table class="comment-table" commentId="571683" commentParentId="571201"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 19:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571683" href="?#comment-571683" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571683" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571683" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571683"> <div class="moveup"> <div class="ttypography"><p>To be honest, I think it very much depends on what you're comfortable with (Specifically, users who love geometry would love this interpretation). For me, it was easier to visualize the problem in the current format (interval format), whereas it took me a while to grasp the rectangle interpretation. It is interesting to see how the problem can be solved in so similar ways for seemingly different interpretations.</p></div> </div> </div> <div class="reply info"> <a class="comment-571683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571683"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="574189" commentParentId="570706"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sthfaceless" style="position: relative;"> <img src='https://userpic.codeforces.org/1176362/avatar/4480df56f05c4612.jpg'/> </a> <div><a href="/profile/sthfaceless" title="Candidate Master sthfaceless" class="rated-user user-violet">sthfaceless</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/18/2020 20:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-574189" href="?#comment-574189" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570706" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="574189" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1176362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-574189"> <div class="moveup"> <div class="ttypography"><p>I used it too :)</p></div> </div> </div> <div class="reply info"> <a class="comment-574189 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-574189 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-574189"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570710" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Radewoosh" style="position: relative;"> <img src='https://userpic.codeforces.org/147752/avatar/a91526f3bd0194e8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570710" href="?#comment-570710" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570710" class="CommentVoteFrame" data-commentRating="76" data-commentUserId="147752" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+76</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570710"> <div class="moveup"> <div class="ttypography"><p>When will we be able to submit?</p></div> </div> </div> <div class="reply info"> <a class="comment-570710 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570710 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570710"> <li> <div class="comment"> <table class="comment-table" commentId="570734" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570734" href="?#comment-570734" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570734" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-38" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570734"> <div class="moveup"> <div class="ttypography"><p>In most contests, submission window opens 2 hours after the contest I guess.</p></div> </div> </div> <div class="reply info"> <a class="comment-570734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570734"> <li> <div class="comment"> <table class="comment-table" commentId="570808" commentParentId="570734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WaterColor2037" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/WaterColor2037" title="Master WaterColor2037" class="rated-user user-orange">WaterColor2037</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570808" href="?#comment-570808" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570808" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="876428" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570808"> <div class="moveup"> <div class="ttypography"><p>Why people downvote this?</p></div> </div> </div> <div class="reply info"> <a class="comment-570808 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570808 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570808"> <li> <div class="comment"> <table class="comment-table" commentId="570811" commentParentId="570808"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:40">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570811" href="?#comment-570811" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570808" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570811" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570811"> <div class="moveup"> <div class="ttypography"><p>Because it isn't true. Usually you can submit a few minutes after system tests are over.</p></div> </div> </div> <div class="reply info"> <a class="comment-570811 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570811 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570811"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570748" commentParentId="570710"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570748" href="?#comment-570748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570710" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570748" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570748"> <div class="moveup"> <div class="ttypography"><p>Now submission is open.</p></div> </div> </div> <div class="reply info"> <a class="comment-570748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570748"> <li> <div class="comment"> <table class="comment-table" commentId="570761" commentParentId="570748"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Kings_Gambit" style="position: relative;"> <img src='https://userpic.codeforces.org/601047/avatar/c3db9b92df80d791.jpg'/> </a> <div><a href="/profile/The_Kings_Gambit" title="Expert The_Kings_Gambit" class="rated-user user-blue">The_Kings_Gambit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570761" href="?#comment-570761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570748" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570761" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="601047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570761"> <div class="moveup"> <div class="ttypography"><p>Exactly 2 hours :)</p></div> </div> </div> <div class="reply info"> <a class="comment-570761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570711" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 18:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570711" href="?#comment-570711" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570711" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570711"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/72725?#comment-570663">Randomised sol for D</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570711 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570711 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570711"> <li> <div class="comment"> <table class="comment-table" commentId="570714" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570714" href="?#comment-570714" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570714" class="CommentVoteFrame" data-commentRating="59" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+59</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570714"> <div class="moveup"> <div class="ttypography"><p>There is another randomized approach involving hashes. You may assign random number to each lecture and then calculate for each interval the xor of numbers assigned to intervals it intersects. Now you should check that every lecture has same hashes in first and second places...</p></div> </div> </div> <div class="reply info"> <a class="comment-570714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570714"> <li> <div class="comment"> <table class="comment-table" commentId="570730" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AsleepAdhyyan" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AsleepAdhyyan" title="Master AsleepAdhyyan" class="rated-user user-orange">AsleepAdhyyan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570730" href="?#comment-570730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="496067" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570730"> <div class="moveup"> <div class="ttypography"><p>how do you calculate the xor of the intersections?</p></div> </div> </div> <div class="reply info"> <a class="comment-570730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570730"> <li> <div class="comment"> <table class="comment-table" commentId="570735" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570735" href="?#comment-570735" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570735" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570735" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570735"> <div class="moveup"> <div class="ttypography"><p>I think, scan-line should work. When the interval $$$[l_i,r_i]$$$ opens, you put $$$h_i$$$ in the position $$$r_i$$$ and when this interval closes you take the xor of all numbers on the $$$[l_i, \infty)$$$.</p><p>It should look like <a href="https://ideone.com/Dypu4W">this</a>, but it gets WA-6 and I'm to sleepy to debug it properly.</p></div> </div> </div> <div class="reply info"> <a class="comment-570735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570735"> <li> <div class="comment"> <table class="comment-table" commentId="570764" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570764" href="?#comment-570764" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570764" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570764"> <div class="moveup"> <div class="ttypography"><p>yeah I did same thing but i get wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570764"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571027" commentParentId="570735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bhj2001" style="position: relative;"> <img src='https://userpic.codeforces.org/602476/avatar/71790bb4a53d93d3.jpg'/> </a> <div><a href="/profile/Bhj2001" title="Master Bhj2001" class="rated-user user-orange">Bhj2001</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571027" href="?#comment-571027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="602476" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571027"> <div class="moveup"> <div class="ttypography"><p>the WA is not because of hash collision <br /> you missed the case when 2 intervals completely overlap</p></div> </div> </div> <div class="reply info"> <a class="comment-571027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571027"> <li> <div class="comment"> <table class="comment-table" commentId="571059" commentParentId="571027"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adamant" style="position: relative;"> <img src='https://userpic.codeforces.org/50468/avatar/69bc1400e66dced8.jpg'/> </a> <div><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571059" href="?#comment-571059" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571027" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571059" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="50468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571059"> <div class="moveup"> <div class="ttypography"><p>Not really, I just made a silly typo in my segment tree code... I got it accepted now: <a href="/contest/1284/submission/68205086" title="Submission 68205086 by adamant">68205086</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571059 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571059 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571059"> <li> <div class="comment"> <table class="comment-table" commentId="576198" commentParentId="571059"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anodaram" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anodaram" title="International Master anodaram" class="rated-user user-orange">anodaram</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/29/2020 08:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576198" href="?#comment-576198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571059" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576198" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="1314285" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-576198"> <div class="moveup"> <div class="ttypography"><p>Segment Tree is more popular way than multiset for this problem, I think.</p></div> </div> </div> <div class="reply info"> <a class="comment-576198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576198"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570740" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amnesiac_dusk" style="position: relative;"> <img src='https://userpic.codeforces.org/630995/avatar/5c9b8d77d7e96eff.jpg'/> </a> <div><a href="/profile/amnesiac_dusk" title="Grandmaster amnesiac_dusk" class="rated-user user-red">amnesiac_dusk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570740" href="?#comment-570740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570740" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="630995" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570740"> <div class="moveup"> <div class="ttypography"><p>It can also be treated as hashing all maximal cliques of the interval graph which should be sufficient for checking the equality of the graphs as the graph is chordal. My code for reference <a href="/contest/1284/submission/68181402" title="Submission 68181402 by amnesiac_dusk">68181402</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570740"> <li> <div class="comment"> <table class="comment-table" commentId="571137" commentParentId="570740"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tejas_919" style="position: relative;"> <img src='https://userpic.codeforces.org/875719/avatar/25f822a14baf7fbf.jpg'/> </a> <div><a href="/profile/tejas_919" title="Master tejas_919" class="rated-user user-orange">tejas_919</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571137" href="?#comment-571137" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571137" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571137"> <div class="moveup"> <div class="ttypography"><p>Can you tell me where can I learn this stuff about graphs? It would be really helpful of you.</p></div> </div> </div> <div class="reply info"> <a class="comment-571137 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571137 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571137"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570799" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/staniewzki" style="position: relative;"> <img src='https://userpic.codeforces.org/838116/avatar/307490effa9e1ae7.jpg'/> </a> <div><a href="/profile/staniewzki" title="Grandmaster staniewzki" class="rated-user user-red">staniewzki</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570799" href="?#comment-570799" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570799" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838116" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570799"> <div class="moveup"> <div class="ttypography"><p>You can look at my submission, I kept two segment trees — in one i put the value of the lecture on the beggining of the lecture and in the other on the end. Then, for each lecture i checked for lectures than do not intersect, so lectures that have end before the current beggining and the same for other side. </p></div> </div> </div> <div class="reply info"> <a class="comment-570799 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570799 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570799"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571124" commentParentId="570730"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nizil" style="position: relative;"> <img src='https://userpic.codeforces.org/250190/avatar/d1314e6f3fecc96f.jpg'/> </a> <div><a href="/profile/Nizil" title="Expert Nizil" class="rated-user user-blue">Nizil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571124" href="?#comment-571124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570730" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571124" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="250190" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571124"> <div class="moveup"> <div class="ttypography"><p>I have a rather neat code doing this that might help: <a href="/contest/1284/submission/68239280" title="Submission 68239280 by Nizil">68239280</a>. I used the formula:</p> <center>$$$\{\text{Lectures that intersect lecture $$$l$$$}\} = \{\text{Lectures that start before $$$l$$$ ends}\} \setminus \{\text{Lectures that end before $$$l$$$ starts}\}$$$</center><p>. Note that if a lecture ends before $$$l$$$ starts, then it also begins before $$$l$$$ ends so in the subtraction every element of the latter set is contained in the former set. Also note that we do a XOR both when we add and when we remove a set.</p></div> </div> </div> <div class="reply info"> <a class="comment-571124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571124"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570746" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570746" href="?#comment-570746" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570746" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570746" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570746"> <div class="moveup"> <div class="ttypography"><p>My solution uses hashes also :)</p><p>Let's calculate value $$$sumA=\sum_{i \, intersects \, j}(h_i\cdot h_j)$$$ by some modulo for segments in A and the same $$$sumB$$$ for segments in B. Here, $$$h_i$$$ are some random values. This can be calculated with scanline. The answer is &quot;YES&quot; iff $$$sumA=sumB$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570746 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570746 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570746"> <li> <div class="comment"> <table class="comment-table" commentId="570766" commentParentId="570746"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570766" href="?#comment-570766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570746" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570766"> <div class="moveup"> <div class="ttypography"><p>yeah me too but i got wa-6</p></div> </div> </div> <div class="reply info"> <a class="comment-570766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570766"> <li> <div class="comment"> <table class="comment-table" commentId="570861" commentParentId="570766"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VladProg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/VladProg" title="Grandmaster VladProg" class="rated-user user-red">VladProg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570861" href="?#comment-570861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570766" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="540941" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570861"> <div class="moveup"> <div class="ttypography"><p>Maybe my code will be helpful: <a href="/contest/1284/submission/68181544" title="Submission 68181544 by VladProg">68181544</a></p><p>It doesn't use any data structures. Only two scan lines.</p></div> </div> </div> <div class="reply info"> <a class="comment-570861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570861"> <li> <div class="comment"> <table class="comment-table" commentId="570871" commentParentId="570861"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BRs82" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BRs82" title="Master BRs82" class="rated-user user-orange">BRs82</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570871" href="?#comment-570871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="778718" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570871"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-570871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570871"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570903" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lemelisk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lemelisk" title="Master lemelisk" class="rated-user user-orange">lemelisk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570903" href="?#comment-570903" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570903" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="513315" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570903"> <div class="moveup"> <div class="ttypography"><p>You can just treat intersections as long number in binary notification (zero means no intersection with given index's segment, one means intersection) and use its remainder as hash. See my submission <a href="https://codeforces.com/contest/1284/submission/68191562">https://codeforces.com/contest/1284/submission/68191562</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570903 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570903 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570903"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571092" commentParentId="570714"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571092" href="?#comment-571092" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570714" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571092" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571092"> <div class="moveup"> <div class="ttypography"><p>I just leave it here. I also assign random number to each lecture, and then calculate some hashes. But to avoid cases when one segment completely inside in other, I just took complement approach. I get hash of all segments that doesn't intersect with selected. They are those who ends before selected, or starts after selected. So, I have two BIT for each place: one for lectures ending at time X and one for lectures starting at time X. This is done with packed coordinates and four BIT for each set of random identifiers. <a href="/contest/1284/submission/68198554" title="Submission 68198554 by r57shell">68198554</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571092 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571092 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571092"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570994" commentParentId="570711"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570994" href="?#comment-570994" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570711" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570994" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570994"> <div class="moveup"> <div class="ttypography"><p>Me too.</p></div> </div> </div> <div class="reply info"> <a class="comment-570994 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570994 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570994"> <li> <div class="comment"> <table class="comment-table" commentId="570995" commentParentId="570994"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gyh20" style="position: relative;"> <img src='https://userpic.codeforces.org/1308908/avatar/4c16031ff5711dd0.jpg'/> </a> <div><a href="/profile/gyh20" title="Legendary Grandmaster gyh20" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>yh20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570995" href="?#comment-570995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570994" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308908" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570995"> <div class="moveup"> <div class="ttypography"><p>My randomised solution also passed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570995"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570712" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/GyojunYoun" style="position: relative;"> <img src='https://userpic.codeforces.org/227186/avatar/84d3b7d6c6ddb05c.jpg'/> </a> <div><a href="/profile/GyojunYoun" title="Grandmaster GyojunYoun" class="rated-user user-red">GyojunYoun</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570712" href="?#comment-570712" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570712" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570712" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="227186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570712"> <div class="moveup"> <div class="ttypography"><p>Thank you for setting these wonderful problems. Unlike other geometry probs, E is so beautiful that I was impressed :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570712 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570712 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570712"> <li> <div class="comment"> <table class="comment-table" commentId="570805" commentParentId="570712"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mango_lassi" style="position: relative;"> <img src='https://userpic.codeforces.org/519408/avatar/69109d1881b4b829.jpg'/> </a> <div><a href="/profile/mango_lassi" title="International Grandmaster mango_lassi" class="rated-user user-red">mango_lassi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570805" href="?#comment-570805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570712" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-29" data-commentUserId="519408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570805"> <div class="moveup"> <div class="ttypography"><p>Just what part of E do you think is beautiful? I agree that the model solution doesn't seem bad, but that is only in comparison to how painful writing code for the not-totally-magic solutions is. A problem with many easy to find ugly solutions does not turn good from the existence of a beautiful solution that is very difficult to find.</p></div> </div> </div> <div class="reply info"> <a class="comment-570805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570805"> <li> <div class="comment"> <table class="comment-table" commentId="570812" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570812" href="?#comment-570812" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570812" class="CommentVoteFrame" data-commentRating="62" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+62</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570812"> <div class="moveup"> <div class="ttypography"><p>I don't get the point. If you failed to find good solution, then it's our fault?</p></div> </div> </div> <div class="reply info"> <a class="comment-570812 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570812 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570812"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570838" commentParentId="570805"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570838" href="?#comment-570838" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570805" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570838" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570838" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570838"> <div class="moveup"> <div class="ttypography"><p>Well, I found it really interesting what you can solve it in $$$O(n^2)$$$. <a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a> is really similar problem and I believe it can only be solved in $$$O(n^3)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570838 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570838 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570838"> <li> <div class="comment"> <table class="comment-table" commentId="570840" commentParentId="570838"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570840" href="?#comment-570840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570838" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570840"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-red" href="/profile/OnionPringles" title="International Grandmaster OnionPringles">OnionPringles</a> told me about the $$$O(n^2\log n)$$$ solution of that problem. Of course, it's much harder than our problem's solution, in any aspect.</p></div> </div> </div> <div class="reply info"> <a class="comment-570840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570840"> <li> <div class="comment"> <table class="comment-table" commentId="570867" commentParentId="570840"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570867" href="?#comment-570867" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570867" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570867"> <div class="moveup"> <div class="ttypography"><p>After I found $$$3x_3+4x_4+5x_5$$$ I thought I need $$$x_5$$$... After 4 TLE attempts, I saw the magic :D</p></div> </div> </div> <div class="reply info"> <a class="comment-570867 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570867 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570867"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570722" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iaNTU" style="position: relative;"> <img src='https://userpic.codeforces.org/568681/avatar/e2c4a458dc77ff9b.jpg'/> </a> <div><a href="/profile/iaNTU" title="International Master iaNTU" class="rated-user user-orange">iaNTU</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570722" href="?#comment-570722" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570722" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-15" data-commentUserId="568681" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-570722"> <div class="moveup"> <div class="ttypography"><p>Seems like you don't understand what &quot;right after&quot; means.</p></div> </div> </div> <div class="reply info"> <a class="comment-570722 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570722 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570722"> <li> <div class="comment"> <table class="comment-table" commentId="570728" commentParentId="570722"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570728" href="?#comment-570728" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570722" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570728" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-16" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570728"> <div class="moveup"> <div class="ttypography"><p>Right after systest. I'm sorry for F.</p></div> </div> </div> <div class="reply info"> <a class="comment-570728 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570728 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570728"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570739" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570739" href="?#comment-570739" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570739" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570739"> <div class="moveup"> <div class="ttypography"><p>Does the following flow solution for F run in time?</p><p>Create three sets of nodes A, B, and C. A represents the first set of edges, C represents the second set of edges. We need to match as many nodes in A as we can with nodes in C. Set B represents all the nodes in the tree. Each node in A and C will be connected to the two nodes that the edge it represents in connected to. We then run flow from the nodes in A to the nodes in C.</p><p>This graph has O(n) edges and a max flow of O(n).</p></div> </div> </div> <div class="reply info"> <a class="comment-570739 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570739 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570739"> <li> <div class="comment"> <table class="comment-table" commentId="570749" commentParentId="570739"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SecondThread" style="position: relative;"> <img src='https://userpic.codeforces.org/512496/avatar/7de9254f7395a47e.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570749" href="?#comment-570749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570739" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="512496" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570749"> <div class="moveup"> <div class="ttypography"><p>Actually, nevermind, this just doesn't work</p></div> </div> </div> <div class="reply info"> <a class="comment-570749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570749"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570743" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/snorkel" style="position: relative;"> <img src='https://userpic.codeforces.org/1360865/avatar/4aa0ab75c5725b5.jpg'/> </a> <div><a href="/profile/snorkel" title="Expert snorkel" class="rated-user user-blue">snorkel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570743" href="?#comment-570743" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360865" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570743"> <div class="moveup"> <div class="ttypography"><p>When the codes will be available?</p></div> </div> </div> <div class="reply info"> <a class="comment-570743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570743"> <li> <div class="comment"> <table class="comment-table" commentId="570767" commentParentId="570743"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 19:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570767" href="?#comment-570767" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570743" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570767" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570767"> <div class="moveup"> <div class="ttypography"><p>Code is available now.</p></div> </div> </div> <div class="reply info"> <a class="comment-570767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570767"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570750" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570750" href="?#comment-570750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570750" class="CommentVoteFrame" data-commentRating="12" 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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570750"> <div class="moveup"> <div class="ttypography"><p>For F we can prove that answer always equals $$$n - 1$$$ easily using Hall theorem. Pick any $$$k$$$ edges in first tree, we want to prove that there are at least $$$k$$$ edges in the second tree which can be used to replace at least one of picked edges. Let's remove all picked edges from the tree, then it splits to $$$k + 1$$$ components. For each edge in the second tree let's draw an edge between components containing endpoints of the edge. Since the tree was connected before compressing edges it is still connected now, which means it has at least $$$k$$$ edges which are not self-loops, which means there are at least $$$k$$$ edges which can be used to replace one of picked edges.</p></div> </div> </div> <div class="reply info"> <a class="comment-570750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570750"> <li> <div class="comment"> <table class="comment-table" commentId="570752" commentParentId="570750"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 19:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570752" href="?#comment-570752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570750" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570752" 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-570752"> <div class="moveup"> <div class="ttypography"><p>Sadly this proof gives no clue on how to find the matching</p></div> </div> </div> <div class="reply info"> <a class="comment-570752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570752"> <li> <div class="comment"> <table class="comment-table" commentId="570774" commentParentId="570752"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570774" href="?#comment-570774" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570774" 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-570774"> <div class="moveup"> <div class="ttypography"><p>In my solution (tl;dr <a href="https://codeforces.com/blog/entry/72725?#comment-570604">here</a>), it just turns out while I'm looking for some characteristics of the matching that it is perfect, and the argument for that is kinda similar to Hall's theorem — it also deals with sets of edges in T2 and adjacent edges in T1. It doesn't seem to be particularly useful for finding a way to compute a matching quickly, though.</p></div> </div> </div> <div class="reply info"> <a class="comment-570774 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570774 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570774"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570772" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 19:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570772" href="?#comment-570772" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570772" class="CommentVoteFrame" data-commentRating="20" 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;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570772"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p><p>Pick a 1 edge (u, v) from the T1, s.t. u is the leaf in T1. We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A). We can find matching, (u, v) in T1 &amp; (u, w) in T2, and remove those edges. For all x($$$x \neq w$$$), if there is a edge (u, x) in T2, we change u to v. it means, remove (u, x) and add(v, x) (step B). As a result, we can remove vertexes u and reduce problem size by one(after operate, T2 remained as tree).</p><p>How to simulate? Bottleneck is the step B, changing (u, x) to (v, x). Therefore we don't change all edges, but simply remove (u, w) and add dummy edge (u, v). We have to find nearest non-dummy edge in step A, but it's all. We can easily do it by Link-Cut Tree</p></div> </div> </div> <div class="reply info"> <a class="comment-570772 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570772 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570772"> <li> <div class="comment"> <table class="comment-table" commentId="570782" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570782" href="?#comment-570782" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570782" 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-570782"> <div class="moveup"> <div class="ttypography"><blockquote><p>We consider a path(u, v) in T2, and take a nearest edge of u in this path(we let (u, w)) (step A).</p> </blockquote><p>Tbh when you have this, there's no need for further tricks or LCT. Just HLD over T1, store not yet taken edges in each path in a set (ordered by depth), DFS over T2 and use HLD to simulate the process for each edge in T2. That's my solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-570782 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570782 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570782"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570785" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OnionPringles" 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/OnionPringles" title="International Grandmaster OnionPringles" class="rated-user user-red">OnionPringles</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570785" href="?#comment-570785" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570785" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="360543" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570785"> <div class="moveup"> <div class="ttypography"><p>I solved step B by merging u,v in T2 by implementing union-find structure on LCT nodes. When merging u and v, cut all preferred children of u and v so that the children can go through union-find structure when they try to access the unpreferred parent. I think it is easy if you have a pre-written LCT code.</p></div> </div> </div> <div class="reply info"> <a class="comment-570785 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570785 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570785"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570791" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gamegame" style="position: relative;"> <img src='https://userpic.codeforces.org/352372/avatar/8717a5b44702348a.jpg'/> </a> <div><a href="/profile/gamegame" title="Legendary Grandmaster gamegame" class="rated-user user-legendary"><span class="legendary-user-first-letter">g</span>amegame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570791" href="?#comment-570791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="352372" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570791"> <div class="moveup"> <div class="ttypography"><p>You can do binary lifting and dsu, which is much more easier to code than LCT/HLD</p></div> </div> </div> <div class="reply info"> <a class="comment-570791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570791"> <li> <div class="comment"> <table class="comment-table" commentId="571082" commentParentId="570791"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 12:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571082" href="?#comment-571082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570791" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571082" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571082"> <div class="moveup"> <div class="ttypography"><p>I had the same, but tbh in such contests it would be more preferable to just copy LCT.</p></div> </div> </div> <div class="reply info"> <a class="comment-571082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571082"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570884" commentParentId="570772"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570884" href="?#comment-570884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570772" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570884" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570884"> <div class="moveup"> <div class="ttypography"><p>I updated my solution to F. It is my favorite in this problem set. Hope you liked it too!</p></div> </div> </div> <div class="reply info"> <a class="comment-570884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570884"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570783" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570783" href="?#comment-570783" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570783" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+61</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570783"> <div class="moveup"> <div class="ttypography"><p>Here is a more intuitive explanation for E. Sorry if it's mentioned already.</p><p>Fix the point $$$p$$$. Translate everything such that $$$p$$$ coincides with the origin. Sort all the other points counter-clockwise. We shall now find the number of quadruples of points that <em>don't</em> form a polygon containing $$$p$$$.</p><p>Now consider some point $$$s$$$. Consider the half-plane $$$H$$$ of points $$$t$$$ such that the cross product $$$s \wedge t$$$ is positive. For a quadrilateral with $$$s$$$ to contain $$$p$$$, it has to have at least one point from $$$H$$$ and at least one point not from $$$H$$$. Conversely, we will count the number of quadruples $$$(s, t_1, t_2, t_3)$$$ such that $$$t_1, t_2, t_3 \in H$$$. It is just the binomial coefficient $$$|H| \choose 3$$$.</p><p>Now do that for all $$$s$$$ and all corresponding $$$H$$$, in linear time, using the two pointers method.</p><p>With iterating over all $$$p$$$ and sorting, the complexity is $$$O (n^2 \log n)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-570783 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570783 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570783"> <li> <div class="comment"> <table class="comment-table" commentId="571005" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLamarca" style="position: relative;"> <img src='https://userpic.codeforces.org/379329/avatar/842836a6a188aadb.jpg'/> </a> <div><a href="/profile/VLamarca" title="Master VLamarca" class="rated-user user-orange">VLamarca</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571005" href="?#comment-571005" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571005" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571005" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="379329" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571005"> <div class="moveup"> <div class="ttypography"><p>This solution works for any size of polygon right? For example if the problem was about triangles instead of quadrilaterals</p><p>thanks for sharing it btw </p></div> </div> </div> <div class="reply info"> <a class="comment-571005 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571005 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571005"> <li> <div class="comment"> <table class="comment-table" commentId="571175" commentParentId="571005"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571175" href="?#comment-571175" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571005" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571175" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571175"> <div class="moveup"> <div class="ttypography"><p>Looks like, yeah, the same argument about all points being in one half-plane would work for pentagons and more.</p><p>Now, if the problem asks for <em>convex</em> polygons, it gets trickier, even with quadrilaterals.</p></div> </div> </div> <div class="reply info"> <a class="comment-571175 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571175 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571175"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571064" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Simurgh" style="position: relative;"> <img src='https://userpic.codeforces.org/1365761/avatar/1d3d3be9bd64e4c9.jpg'/> </a> <div><a href="/profile/Simurgh" title="Expert Simurgh" class="rated-user user-blue">Simurgh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571064" href="?#comment-571064" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571064" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1365761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571064"> <div class="moveup"> <div class="ttypography"><p>Where can I learn more about cross products of vectors and how they can be used in geometry problems?</p></div> </div> </div> <div class="reply info"> <a class="comment-571064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571064"> <li> <div class="comment"> <table class="comment-table" commentId="571178" commentParentId="571064"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Gassa" style="position: relative;"> <img src='https://userpic.codeforces.org/111/avatar/eee0360a64e01cd1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Gassa" title="International Master Gassa" class="rated-user user-orange">Gassa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571178" href="?#comment-571178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571064" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="111" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571178"> <div class="moveup"> <div class="ttypography"><p>Basically, scalar product and cross product are similar in behavior to cosine and sine of angle between vectors, respectively. Their signs behave the same.</p><p>The upside is that, more often than not, we are given coordinates of points as integers (or rationals). And computing scalar and cross products can be done using integers only. So we don't have to resort to floating point and then deal with a whole additional class of errors because of loss of precision.</p><p>As for more general overview, a <a href="https://www.google.com/search?q=scalar+product+and+cross+product+in+computational+geometry">Google search</a> lands some nice articles on the first page.</p></div> </div> </div> <div class="reply info"> <a class="comment-571178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571178"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571093" commentParentId="570783"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 13:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571093" href="?#comment-571093" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570783" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571093" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571093" class="CommentVoteFrame" data-commentRating="10" 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: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-571093"> <div class="moveup"> <div class="ttypography"><p>How can I actually easily find the sign of the cross product between two vectors? I got an idea of how to do it with the angle between them, but it seems ugly and probably prone to bugs.</p><p>Edit: I found a way on <a href="https://en.wikipedia.org/wiki/Cross_product#Computational_geometry">Wikipedia</a>, scroll down to the Computation Geometry section.</p></div> </div> </div> <div class="reply info"> <a class="comment-571093 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571093 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571093"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570787" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/undisputedAshu" style="position: relative;"> <img src='https://userpic.codeforces.org/327726/avatar/92b4b2153c6ba4e4.jpg'/> </a> <div><a href="/profile/undisputedAshu" title="Pupil undisputedAshu" class="rated-user user-green">undisputedAshu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570787" href="?#comment-570787" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570787" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="327726" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570787"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain for B</p><p>3</p><p>4 2 0 2 0</p><p>6 9 9 8 8 7 7</p><p>1 6</p><p>how is it 7?</p></div> </div> </div> <div class="reply info"> <a class="comment-570787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570787"> <li> <div class="comment"> <table class="comment-table" commentId="570793" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/djm03178" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/djm03178" title="Master djm03178" class="rated-user user-orange">djm03178</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570793" href="?#comment-570793" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570793" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="687688" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570793"> <div class="moveup"> <div class="ttypography"><p>Let's say a = [2,0,2,0], b = [9,9,8,8,7,7], c = [6], then the answers are: aa, ab, ac, ba, bb, ca, and cb.</p></div> </div> </div> <div class="reply info"> <a class="comment-570793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570793"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570794" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gol_en_05" style="position: relative;"> <img src='https://userpic.codeforces.org/838032/avatar/8167074e5c48a57d.jpg'/> </a> <div><a href="/profile/gol_en_05" title="Specialist gol_en_05" class="rated-user user-cyan">gol_en_05</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570794" href="?#comment-570794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570794" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="838032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570794"> <div class="moveup"> <div class="ttypography"><p>since 2 0 2 0 has an ascent.so total pairs are 3. 2 nd sequence does not have an ascent but pairs (2,2),(2,1) has ascent. similarly for 3rd sequence pairs(3,1) and(3,2) has ascent. so total 7 pairs are possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-570794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570794"> <li> <div class="comment"> <table class="comment-table" commentId="570904" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570904" href="?#comment-570904" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570904" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570904"> <div class="moveup"> <div class="ttypography"><p>I'm struggling to understand what does &quot;but pairs (2,2),(2,1) has ascent&quot; mean. Can you please elaborate? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-570904 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570904 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570904"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570916" commentParentId="570794"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ninilo97" style="position: relative;"> <img src='https://userpic.codeforces.org/1151463/avatar/6707509d0c8f99f4.jpg'/> </a> <div><a href="/profile/ninilo97" title="Pupil ninilo97" class="rated-user user-green">ninilo97</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570916" href="?#comment-570916" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570794" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570916" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1151463" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570916"> <div class="moveup"> <div class="ttypography"><p>Thanks I got it!</p></div> </div> </div> <div class="reply info"> <a class="comment-570916 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570916 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570916"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570795" commentParentId="570787"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/BOGDAN_" 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/BOGDAN_" title="Expert BOGDAN_" class="rated-user user-blue">BOGDAN_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570795" href="?#comment-570795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570787" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570795" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="635882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570795"> <div class="moveup"> <div class="ttypography"><p>Let 1, 2, 3 — indexes of arrays. Here is &quot;1 + 2&quot;</p><p>&quot;1 + 3&quot;</p><p>&quot;1 + 1&quot;</p><p>&quot;2 + 2&quot;</p><p>&quot;2 + 1&quot;</p><p>&quot;3 + 1&quot;</p><p>&quot;3 + 2&quot;</p><p>At all — answer 7.</p></div> </div> </div> <div class="reply info"> <a class="comment-570795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570803" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Wa-Automaton" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Wa-Automaton" title="Candidate Master Wa-Automaton" class="rated-user user-violet">Wa-Automaton</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570803" href="?#comment-570803" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570803" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570803" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1365147" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570803"> <div class="moveup"> <div class="ttypography"><p>For D, removing operation is at time ea_i + 1 ?</p><p>UPD: It's fixed.</p></div> </div> </div> <div class="reply info"> <a class="comment-570803 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570803 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570803"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570816" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570816" href="?#comment-570816" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570816" 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="570816" 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-570816"> <div class="moveup"> <div class="ttypography"><p>D can be solved using &quot;Job scheduling &quot; algorithm. Initially we check all the intervals for both the venues individually,whether they overlap,if we get different answer,answer is &quot;NO&quot;.</p><p>If we get same answer and both timings of both venues don't overlap,then answer is &quot;YES&quot;.</p><p>If we get &quot;over-lap&quot; for both,there is a possibility that removing some lectures might make one venue overlapping and other non_overlapping</p><p>eg: 1 2 3 4</p> <pre>3 4 4 5 4 5 6 7</pre><p>In this case,we use job scheduling algorithm to find the largest no of lectures that can be present such that,lecture timings don't overlap for venue A.</p><p>Keep only those lectures for B,check if answer is different for both venues,do the same thing for venue B.</p><p><a href="/contest/1284/submission/68206806" title="Submission 68206806 by AjaySabarish">68206806</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570816 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570816 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570816"> <li> <div class="comment"> <table class="comment-table" commentId="571060" commentParentId="570816"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 11:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571060" href="?#comment-571060" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570816" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571060" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571060"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/AjaySabarish" title="Expert AjaySabarish">AjaySabarish</a> Hi, can you please explain the part about &quot;non over-lap&quot; in a little detail?How is there a possibility that removing some lectures might make one venue overlapping and other non_overlapping? I also thought about job scheduling algo but as mentioned in comments, did not consider such cases like finding interval in a and then checking them in b and vice versa. Do they both not give same result? </p></div> </div> </div> <div class="reply info"> <a class="comment-571060 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571060 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571060"> <li> <div class="comment"> <table class="comment-table" commentId="571066" commentParentId="571060"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 11:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571066" href="?#comment-571066" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571060" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571066" 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-571066"> <div class="moveup"> <div class="ttypography"><p>Sry there was a typo,now corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-571066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571066"> <li> <div class="comment"> <table class="comment-table" commentId="571198" commentParentId="571066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishtha1896" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/nishtha1896" title="Newbie nishtha1896" class="rated-user user-gray">nishtha1896</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571198" href="?#comment-571198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="406730" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571198"> <div class="moveup"> <div class="ttypography"><p>Still can you explain that point about removing some lectures?</p></div> </div> </div> <div class="reply info"> <a class="comment-571198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571198"> <li> <div class="comment"> <table class="comment-table" commentId="571219" commentParentId="571198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571219" href="?#comment-571219" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571219" 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-571219"> <div class="moveup"> <div class="ttypography"><p>Consider the above example,which I gave </p><p>3</p><p>1 2 3 4</p><p>3 4 4 5</p><p>4 5 6 7</p><p>Now,the timings overlap for both venues,but if you remove lecture 3,timings dont overlap for venue A but overlap for venue B.</p><p>This is the last case which I was talking about,now you have to use job scheduling to find the answer.</p><p>Find the highest number of non overlapping segments for A,it is lecture 1,2.</p><p>Now keep only these lectures for both venues,now the segments for B should also not overlap for &quot;not venue sensitive&quot;. But it is overlapping,so it is venue sensitive</p></div> </div> </div> <div class="reply info"> <a class="comment-571219 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571219 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571219"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570825" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SajidZakaria" style="position: relative;"> <img src='https://userpic.codeforces.org/553136/avatar/f6d8cc00ec65b842.jpg'/> </a> <div><a href="/profile/SajidZakaria" title="Candidate Master SajidZakaria" class="rated-user user-violet">SajidZakaria</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570825" href="?#comment-570825" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570825" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="553136" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570825"> <div class="moveup"> <div class="ttypography"><p>The test cases in D were very &quot;weak&quot;. My solution : <a href="/contest/1284/submission/68205621" title="Submission 68205621 by SajidZakaria">68205621</a></p><p>For very large N, it's enough to only check if each of the lectures have the same number of intersections in A and B. Taking advantage of the fact that it's hard to put up a test case that avoids being fooled that way.</p></div> </div> </div> <div class="reply info"> <a class="comment-570825 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570825 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570825"> <li> <div class="comment"> <table class="comment-table" commentId="634898" commentParentId="570825"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Prajwal_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Prajwal_" title="Expert Prajwal_" class="rated-user user-blue">Prajwal_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/02/2020 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-634898" href="?#comment-634898" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570825" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="634898" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1360518" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-634898"> <div class="moveup"> <div class="ttypography"><p>but how will you calculate the intersections in O(n) time.Can you explain once more??</p></div> </div> </div> <div class="reply info"> <a class="comment-634898 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-634898 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-634898"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570829" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570829" href="?#comment-570829" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570829" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570829"> <div class="moveup"> <div class="ttypography"><p>Can you share other solutions to E? Except <a class="rated-user user-orange" href="/profile/Gassa" title="International Master Gassa">Gassa</a>'s (above)</p></div> </div> </div> <div class="reply info"> <a class="comment-570829 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570829 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570829"> <li> <div class="comment"> <table class="comment-table" commentId="570852" commentParentId="570829"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570852" href="?#comment-570852" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570829" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570852" 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="570852" class="CommentVoteFrame" data-commentRating="45" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+45</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570852"> <div class="moveup"> <div class="ttypography"><p>I'll put it short:</p> <ul> <li>(By <a class="rated-user user-red" href="/profile/kdh9949" title="International Grandmaster kdh9949">kdh9949</a> <a class="rated-user user-orange" href="/profile/jihoon" title="International Master jihoon">jihoon</a>) Find $$$f(p)$$$ for each point. You can see that the set can enclose $$$p$$$ iff its convex hull contains $$$p$$$. Checking the containment is hard, so sort by angle, and eliminate the set that does not contain $$$p$$$, which reduces to almost similar sweep with model code. I think this is the easiest solution to come up with.</li> <li>(By <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a>) The answer depends on the 2 * (number of convex quadrilaterals) + (number of concave quadrilaterals). We denote this number $$$A$$$. I think the answer is $$$(A - 2\binom{n}{4}) \times (n-4)/2$$$, or something like that. This problem is bit harder, so you need another type of angular sweep like JOI Open 2017 Bulldozer. I think this is more involved to code, but our great tester <a class="rated-user user-legendary" href="/profile/molamola." title="Legendary Grandmaster molamola."><span class="legendary-user-first-letter">m</span>olamola.</a> took exactly 12 minutes to AC this.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-570852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570852"> <li> <div class="comment"> <table class="comment-table" commentId="571006" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/NoLongerRed" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/NoLongerRed" title="Grandmaster NoLongerRed" class="rated-user user-red">NoLongerRed</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571006" href="?#comment-571006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571006" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="567645" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571006"> <div class="moveup"> <div class="ttypography"><p>My solution is pretty much the same as molamola's solution and I think it is not necessary to do a cool angular sweep:<br />Let $$$X$$$ be the number of $$$((A,B,C),D)$$$ such that $$$D$$$ lies in $$$ABC$$$ and $$$(A,B,C)$$$ is an unordered tuple. The answer is $$$(n-4)X/2$$$.<br />$$$X$$$ can be counted easily: fixing $$$D$$$ and sort other points by the angles, then do a bunch of lower bound.</p></div> </div> </div> <div class="reply info"> <a class="comment-571006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571006"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571012" commentParentId="570852"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Temirulan" style="position: relative;"> <img src='https://userpic.codeforces.org/25825/avatar/3460c3ba45d88ec0.jpg'/> </a> <div><a href="/profile/Temirulan" title="Expert Temirulan" class="rated-user user-blue">Temirulan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571012" href="?#comment-571012" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570852" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571012" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="25825" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571012"> <div class="moveup"> <div class="ttypography"><p>Thanks for sharing. The solution in Editorial really beautiful, but I don't know. Is that possible to came up with such solution in ~1 hour?</p></div> </div> </div> <div class="reply info"> <a class="comment-571012 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571012 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571012"> <li> <div class="comment"> <table class="comment-table" commentId="571014" commentParentId="571012"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 06:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571014" href="?#comment-571014" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571012" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571014" 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="571014" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571014"> <div class="moveup"> <div class="ttypography"><p>Actually my solution submitted during the contest is exactly same as the tutorial solution. In fact, I tried to compute all of $$$x$$$, $$$y$$$, and $$$z$$$, so I double-counted not only the edges of the convex hull but also the diagonal edges, to obtain three linear equations.</p> <center>$$$ x + y + z = {n \choose 5} \\ 5x + 4y + 3z = sth \\ 5x + 6y + 7z = sth $$$</center><p>Unfortunately, this linear system was undetermined, and all I can get was $$$(y + 2z)$$$. That was when I felt quite disappointed. But surprisingly, the answer to the problem happened to be exactly $$$(y + 2z)$$$, so I could finally solve the problem.</p><p>At first, I thought I was lucky enough to find a solution with such unsolvable system. So I headed to this tutorial to read the &quot;official&quot; solution, only to find my solution again. Thanks to your question, I found it in the comments :-)</p><p><a href="/contest/1284/submission/68196878" title="Submission 68196878 by jo_on">68196878</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571014 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571014 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571014"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570830" commentParentId="-1"> <tr> <td class="left"> <div style="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="Jan/04/2020 20:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570830" href="?#comment-570830" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570830" class="CommentVoteFrame" data-commentRating="3" 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: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-570830"> <div class="moveup"> <div class="ttypography"><p>Just curious,did everyone who solved C in contest,prove the solution?It was not so obvious to me,deciphering and processing what a &quot;framed segment&quot; is,took a lot of time.</p><p>Finding pattern was quite difficult,as manually generating test case even for n=4 is difficult</p><p>Lot of people solved it,is there any other idea?</p></div> </div> </div> <div class="reply info"> <a class="comment-570830 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570830 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570830"> <li> <div class="comment"> <table class="comment-table" commentId="570899" commentParentId="570830"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570899" href="?#comment-570899" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570830" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570899" class="CommentVoteFrame" data-commentRating="2" 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:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570899"> <div class="moveup"> <div class="ttypography"><p>Hi, If you now know what a &quot;framed segment&quot; is, then try to formulate number of &quot;framed segment&quot; of a particular length for a given n. For example: if we want to count &quot;framed segement&quot; of length 1. Let's first consider all &quot;framed segment&quot; containing only digit 1. For this &quot;framed segment&quot; to be at leftmost, there are (n — 1)! permutations. Similar argument goes for its other positions as well. This gives us count : (n — 1)! * n. Now, there are total of n single digits like &quot;1&quot; which can make single length &quot;framed segement&quot;. Thus now count for all single length &quot;framed segement&quot; is : (n — 1)! * n * n (something missing?). I have tried to explain the solution with single length fragment above with some details missing which I think you will figure out. Please try to come-up with a general formulation for any &quot;framed segment&quot;length x for a given n. Summing it all up will give you the answer. Link to my submission : <a href="https://codeforces.com/contest/1284/submission/68187501">Here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570899 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570899 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570899"> <li> <div class="comment"> <table class="comment-table" commentId="570912" commentParentId="570899"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570912" href="?#comment-570912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570899" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570912" 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-570912"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot,I get the solution,but I am just curious about the high number of submissions,was it so obvious?did everyone actually prove it or used their intuition to get it?</p></div> </div> </div> <div class="reply info"> <a class="comment-570912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570912"> <li> <div class="comment"> <table class="comment-table" commentId="570917" commentParentId="570912"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570917" href="?#comment-570917" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570912" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570917" 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-570917"> <div class="moveup"> <div class="ttypography"><p>I guess that depends on one's way of counting up to the answer. And from the number of submissions, it feels like people are actually good at counting..:P</p></div> </div> </div> <div class="reply info"> <a class="comment-570917 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570917 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570917"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kiimak" style="position: relative;"> <img src='https://userpic.codeforces.org/780779/avatar/9d6b81e1dd625cd6.jpg'/> </a> <div><a href="/profile/kiimak" title="Candidate Master kiimak" class="rated-user user-violet">kiimak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570849" href="?#comment-570849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570849" 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="570849" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="780779" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570849"> <div class="moveup"> <div class="ttypography"><p>Hi, I think I found a test case for problem D where my solution gets accepted but it should be incorrect.</p> <pre><code>5 1 10 1 10 2 20 11 30 11 30 2 20 21 40 21 40 31 50 31 50 </code></pre><p>I've checked with the code given in the tutorial, the answer is NO, but my solution gives YES. <a href="/contest/1284/submission/68207409" title="Submission 68207409 by kiimak">68207409</a></p><p>I've modeled it as a graph and put an edge (u, v) if lecture u and v meet. I thought it would be enough to check two things for graph A and B (venue A and B)</p> <ul> <li>the number of degrees for each lecture</li> <li>the lecture set of each component</li> </ul><p>I've submitted it after the contest so it doesn't effect my ratings, but I thought it was worth mentioning.</p></div> </div> </div> <div class="reply info"> <a class="comment-570849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570849"> <li> <div class="comment"> <table class="comment-table" commentId="570891" commentParentId="570849"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ormlis" style="position: relative;"> <img src='https://userpic.codeforces.org/1250517/avatar/5b32008c179f4f98.jpg'/> </a> <div><a href="/profile/Ormlis" title="Legendary Grandmaster Ormlis" class="rated-user user-legendary"><span class="legendary-user-first-letter">O</span>rmlis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570891" href="?#comment-570891" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570891" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1250517" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570891"> <div class="moveup"> <div class="ttypography"><p>I made the same mistake. I tried to find a test case where this is not true, but I could not. Thanks you</p></div> </div> </div> <div class="reply info"> <a class="comment-570891 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570891 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570891"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DJoker99" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/DJoker99" title="Pupil DJoker99" class="rated-user user-green">DJoker99</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:30">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570865" href="?#comment-570865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570865" 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="570865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="886083" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570865"> <div class="moveup"> <div class="ttypography"><p>Solution for B [Best :- O(n) Worst :- O(nlogn)]</p><p><a href="https://codeforces.com/contest/1284/submission/68210022">https://codeforces.com/contest/1284/submission/68210022</a></p><p>The condition for a non-ascent sequence a and a non-ascen sequence b to form an ascenting sequence is</p><p><code>min(a) &lt;max(b)</code></p> <ol> <li>First traverse the lists and store max and min in two separate vectors.</li> <li>if a sequence has ascent ie if an element greater than current min or current max occurs then that sequence will always give an ascenting sequence hence do <code>cnt = cnt + 2*n-1</code> <code>n--;</code> because that sequence will form 2n-1 sequences on concatenation</li> <li><p>Sort the max and min vectors then use two pointer approach.</p></li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-570865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570865"> <li> <div class="comment"> <table class="comment-table" commentId="570973" commentParentId="570865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 00:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570973" href="?#comment-570973" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570865" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570973" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570973" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570973"> <div class="moveup"> <div class="ttypography"><p>Involving sort gives already nlogn solution) - <a href="https://codeforces.com/contest/1284/submission/68206308">my code</a> — P. S. I have similar solution, but simpler.</p></div> </div> </div> <div class="reply info"> <a class="comment-570973 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570973 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570973"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570877" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prateek_aries" style="position: relative;"> <img src='https://userpic.codeforces.org/780171/avatar/c6136d0edef16466.jpg'/> </a> <div><a href="/profile/prateek_aries" title="Expert prateek_aries" class="rated-user user-blue">prateek_aries</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570877" href="?#comment-570877" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570877" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="780171" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570877"> <div class="moveup"> <div class="ttypography"><p>Someone please explain me the meaning of the last statement in C. &quot;By observing that there exist exactly n−len+1 pairs with 1≤l≤r≤n,r−l+1=len, we can simply multiply this number for each length, giving a O(n) time solution.&quot; Please give any example.</p></div> </div> </div> <div class="reply info"> <a class="comment-570877 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570877 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570877"> <li> <div class="comment"> <table class="comment-table" commentId="570981" commentParentId="570877"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SinKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SinKing" title="Specialist SinKing" class="rated-user user-cyan">SinKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570981" href="?#comment-570981" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570877" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570981" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="902209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570981"> <div class="moveup"> <div class="ttypography"><p>Example of what is it about: </p><p>Consider n of 5 and len of 3</p> <ul> <li><p>1 2 3</p></li> <li><p>2 3 4</p></li> <li><p>3 4 5</p></li> </ul><p>Permutate each of them, and you will get all framed subarrays for n and len of the example. </p></div> </div> </div> <div class="reply info"> <a class="comment-570981 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570981 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570981"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570883" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/im_sanyam" style="position: relative;"> <img src='https://userpic.codeforces.org/605247/avatar/6943d67eaf1d4243.jpg'/> </a> <div><a href="/profile/im_sanyam" title="Expert im_sanyam" class="rated-user user-blue">im_sanyam</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 21:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570883" href="?#comment-570883" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570883" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="605247" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570883"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain to me the solution of problem C in a better and intuitive way?</p></div> </div> </div> <div class="reply info"> <a class="comment-570883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570883"> <li> <div class="comment"> <table class="comment-table" commentId="570902" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570902" href="?#comment-570902" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="570902" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="570902" 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-570902"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570902 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570902 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570902"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="570911" commentParentId="570883"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/meiniak" style="position: relative;"> <img src='https://userpic.codeforces.org/803808/avatar/924fee722719da18.jpg'/> </a> <div><a href="/profile/meiniak" title="Newbie meiniak" class="rated-user user-gray">meiniak</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570911" href="?#comment-570911" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570883" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570911" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="803808" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570911"> <div class="moveup"> <div class="ttypography"><p>let's take n = 5. ar = [1,2,3,4,5] . Now iterate for all possible length of sub-array and count number of good sub-array for that length. k = 1, 2, 3 and so on.</p><p>let take say k = 2 and n = 5. So there are n-k+1 position possible to place k elements i.e If we consider [1,2] then we can place [1,2] in position _ 3 _ 4 _ 5 _ and you can select (n-k+1) elements from n elements to i.e [1,2] , [2,3] , [3,4] and [4,5] . So this is how we got (n-k+1) * (n-k+1) and now we just have to count number of possible permutation of k and (n-k) elements left which is nothing but k! and (n-k)! .** (n-k+1) * (n-k+1) * k! * (n-k)!** is the total answer</p></div> </div> </div> <div class="reply info"> <a class="comment-570911 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570911 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570911"> <li> <div class="comment"> <table class="comment-table" commentId="647624" commentParentId="570911"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lazy_learner" style="position: relative;"> <img src='https://userpic.codeforces.org/926934/avatar/1c97e4ddf06e9813.jpg'/> </a> <div><a href="/profile/lazy_learner" title="Newbie lazy_learner" class="rated-user user-gray">lazy_learner</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2020 08:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-647624" href="?#comment-647624" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570911" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="647624" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926934" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-647624"> <div class="moveup"> <div class="ttypography"><p>But would that not lead to overcounting.<br />Consider the case 3 (1 2) 4 5 and 3 1 2 (4 5).<br />These 2 permutations are same and will be counted twice, once when we consider 1,2 together and second when 4,5 are taken together.</p></div> </div> </div> <div class="reply info"> <a class="comment-647624 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-647624 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-647624"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570914" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rover1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rover1" title="Specialist rover1" class="rated-user user-cyan">rover1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570914" href="?#comment-570914" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570914" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1239447" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570914"> <div class="moveup"> <div class="ttypography"><p>If in question C, we have given a permutation of length n then we need to find happiness... Anyone want to share their approaches ..</p></div> </div> </div> <div class="reply info"> <a class="comment-570914 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570914 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570914"> <li> <div class="comment"> <table class="comment-table" commentId="570918" commentParentId="570914"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/04/2020 22:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570918" href="?#comment-570918" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570914" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570918" 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-570918"> <div class="moveup"> <div class="ttypography"><p>I have tried to explain in my comment : <a href="https://codeforces.com/blog/entry/72804?#comment-570899">https://codeforces.com/blog/entry/72804?#comment-570899</a>. I hope it's helpful</p></div> </div> </div> <div class="reply info"> <a class="comment-570918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570918"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570927" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/M1v1savva1601" style="position: relative;"> <img src='https://userpic.codeforces.org/539005/avatar/21949389dc808e09.jpg'/> </a> <div><a href="/profile/M1v1savva1601" title="Master M1v1savva1601" class="rated-user user-orange">M1v1savva1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 22:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570927" href="?#comment-570927" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570927" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="539005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570927"> <div class="moveup"> <div class="ttypography"><p>Shouldn't it be <strong>eai + 1</strong> in D tutorial?</p></div> </div> </div> <div class="reply info"> <a class="comment-570927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570927"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570941" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AwakeAnay" style="position: relative;"> <img src='https://userpic.codeforces.org/666008/avatar/7043fde46ee0493c.jpg'/> </a> <div><a href="/profile/AwakeAnay" title="Grandmaster AwakeAnay" class="rated-user user-red">AwakeAnay</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2020 23:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570941" href="?#comment-570941" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="666008" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570941"> <div class="moveup"> <div class="ttypography"><p>I had a overkill solution for $$$D$$$ which led to a good data structures problem. While, others have provided much more elegant solutions, this reduced version is a good problem on its own and worth sharing.</p><p>Here's the problem:</p><p>You are given two sequences $$$a_i$$$ and $$$b_i$$$ of length $$$2N$$$ each. Each number from $$$1$$$ to $$$N$$$ appears exactly twice in both the sequences. You have to solve $$$Q$$$ queries of the following kind:</p><p>Given $$$l$$$, $$$r$$$, $$$x$$$ and $$$y$$$, find the set of distinct elements in $$$(l, r)$$$ in $$$a$$$ is exactly equal to the set of distinct elements in $$$(x, y)$$$ in $$$b$$$. That is, any number $$$u$$$ has an appearance in segment $$$(l, r)$$$ in $$$a$$$ if and only if it has an appearance in segment $$$(x, y)$$$ in $$$b$$$. Try to solve this online in $$$O((N+Q)\log(N))$$$.</p><p>Think of how you can reduce today's $$$D$$$ into this problem.</p><p>My code for today's D: <a href="/contest/1284/submission/68189310" title="Submission 68189310 by AwakeAnay">68189310</a></p></div> </div> </div> <div class="reply info"> <a class="comment-570941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570941"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570975" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/madhav_1999" style="position: relative;"> <img src='https://userpic.codeforces.org/594602/avatar/cad96e04d2a42e66.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/madhav_1999" title="Master madhav_1999" class="rated-user user-orange">madhav_1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 01:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570975" href="?#comment-570975" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570975" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="594602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570975"> <div class="moveup"> <div class="ttypography"><p>In D: &quot;Event removing interval [sbi, ebi] from S at time ebi+1.&quot;</p><p><a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a>, I think you made an error here, it should be eai + 1 instead</p></div> </div> </div> <div class="reply info"> <a class="comment-570975 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570975 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570975"> <li> <div class="comment"> <table class="comment-table" commentId="571032" commentParentId="570975"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571032" href="?#comment-571032" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570975" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571032" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571032"> <div class="moveup"> <div class="ttypography"><p>Sorry, fixed. </p></div> </div> </div> <div class="reply info"> <a class="comment-571032 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571032 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571032"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="570982" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 02:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570982" href="?#comment-570982" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570982" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-570982"> <div class="moveup"> <div class="ttypography"><p>Problem B can also be solved in $$$O(n)$$$. Be $$$asc$$$ the number of sequences that have an ascent. For each sequence, check if it's non-increasing. If it isn't any concatenation we do will have an ascent, so we can add $$$n$$$ to our answer and $$$1$$$ to $$$asc$$$. Now be $$$s$$$ a non-increasing sequence and let's set it as the right part of the concatenation. We will only have an ascent in the concatenation if the left part already has an ascent or has an element smaller than any element in $$$s$$$, specially it's maximum. We have $$$asc$$$ sequences of the first type, so that's easy, and for the second part we can precalculate it by creating an array $$$minfreq$$$ where we store the minimum of each non-increasing sequence in it's position (as $$$s_{i,j} &lt; 10^6$$$) and do a sweep from $$$1$$$ to $$$10^6$$$ to accumulate our sum ($$$minfreq[i] = minfreq[i-1] +minfreq[i]$$$). Now we have our answer for the second part in position $$$minfreq[max(s)-1]$$$, and we can just add both parts to our answer. Since we can precalculate $$$minfreq$$$, $$$max(s)$$$ and $$$asc$$$ in $$$O(n)$$$ and the answer can be calculated in $$$O(1)$$$ using our precalculations total complexity is $$$O(n)$$$ </p></div> </div> </div> <div class="reply info"> <a class="comment-570982 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570982 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570982"> <li> <div class="comment"> <table class="comment-table" commentId="570987" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dblark" style="position: relative;"> <img src='https://userpic.codeforces.org/693276/avatar/70323ef41e4c9add.jpg'/> </a> <div><a href="/profile/dblark" title="International Master dblark" class="rated-user user-orange">dblark</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 03:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-570987" href="?#comment-570987" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="570987" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="693276" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-570987"> <div class="moveup"> <div class="ttypography"><p>Yeah, the same idea with you!</p></div> </div> </div> <div class="reply info"> <a class="comment-570987 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-570987 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-570987"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571037" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Jan/05/2020 08:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571037" href="?#comment-571037" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571037" class="CommentVoteFrame" data-commentRating="0" 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:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571037"> <div class="moveup"> <div class="ttypography"><p>I did the same, but this is not O(N). The time Complexity will be O(n + maxELE) where maxELE is the largest sequence element seen in input.</p><p>We were lucky that the constraint on that wasn't 10^9.</p><p>Also consider cases in which n = 5 but the elements are still very large, our code would still take lot of time to execute.</p></div> </div> </div> <div class="reply info"> <a class="comment-571037 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571037 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571037"> <li> <div class="comment"> <table class="comment-table" commentId="571654" commentParentId="571037"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 18:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571654" href="?#comment-571654" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571037" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571654" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571654"> <div class="moveup"> <div class="ttypography"><p>Yeah that's true, the editorial's solution is more general for that same reason</p></div> </div> </div> <div class="reply info"> <a class="comment-571654 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571654 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571654"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571551" commentParentId="570982"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571551" href="?#comment-571551" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-570982" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571551" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571551"> <div class="moveup"> <div class="ttypography"><p>I cant understand the minfreq[i]=minfreq[i−1]+minfreq[i] . can you explain me </p></div> </div> </div> <div class="reply info"> <a class="comment-571551 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571551 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571551"> <li> <div class="comment"> <table class="comment-table" commentId="571653" commentParentId="571551"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bentoper" style="position: relative;"> <img src='https://userpic.codeforces.org/714702/avatar/194d69d089eb7154.jpg'/> </a> <div><a href="/profile/bentoper" title="Expert bentoper" class="rated-user user-blue">bentoper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571653" href="?#comment-571653" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571551" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571653" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571653"> <div class="moveup"> <div class="ttypography"><p>It's called accumulated sum. Basically we want minfreq[i] to be the frequency of all numbers $$$\leq$$$ to i, so we need to push our previous array position to our current one, so that we also take into account the occurences of numbers &lt; i, and not just equal to i</p></div> </div> </div> <div class="reply info"> <a class="comment-571653 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571653 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571653"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571001" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Aguin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Aguin" title="Candidate Master Aguin" class="rated-user user-violet">Aguin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 04:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571001" href="?#comment-571001" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571001" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="297931" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571001"> <div class="moveup"> <div class="ttypography"><p>How to count different quadrilaterals in problem E?</p></div> </div> </div> <div class="reply info"> <a class="comment-571001 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571001 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571001"> <li> <div class="comment"> <table class="comment-table" commentId="571004" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tutis" style="position: relative;"> <img src='https://userpic.codeforces.org/473222/avatar/13ed23859434ec97.jpg'/> </a> <div><a href="/profile/Tutis" title="International Master Tutis" class="rated-user user-orange">Tutis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571004" href="?#comment-571004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="473222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571004"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1146/problem/H" title="Forethought Future Cup - Elimination Round">1146H - Satanic Panic</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571004"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="571007" commentParentId="571001"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Jan/05/2020 05:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571007" href="?#comment-571007" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571001" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571007" class="CommentVoteFrame" data-commentRating="3" 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;">+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-571007"> <div class="moveup"> <div class="ttypography"><p>For example, for each pair of points $$$(i, j)$$$, we can find the number of points on one side of the line i-j ($$$a$$$), the number of points on the other side ($$$N-2-a$$$), sum that up, divide by 2 and subtract $$$2{N\choose 4}$$$. Why? For each 4-tuple of points, if one of them is inside the triangle formed by the other 3 (their convex hull is a triangle), we get 3 lines (inner point, some other point) that are counted here, and when their convex hull is a quadrilateral, we get 2 such lines — its diagonals; we subtract (2 * number of 4-tuples) to get the number of 4-tuples where one point is inside.</p><p>How to find these $$$a$$$ for each pair $$$(i, j)$$$ fast? Let's say that $$$i$$$ is fixed, sort all remaining points by their angle around point $$$i$$$, then consider a line that crosses $$$i$$$, start rotating it and whenever it crosses one of these points, update the current value of $$$a$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-571007 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571007 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571007"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571011" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 05:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571011" href="?#comment-571011" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571011" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571011"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> (<a href="/topic/73334/en9">previous revision</a>, <a href="/topic/73334/en10">new revision</a>, <a href="/topic/73334/diff/en9/en10">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-571011 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571011 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571011"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hd7" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Hd7" title="Specialist Hd7" class="rated-user user-cyan">Hd7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 07:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571018" href="?#comment-571018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571018" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="559666" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571018"> <div class="moveup"> <div class="ttypography"><p>Could anyone give me a more elaborated explanation for problem D, I didn't grasp the editorial at all.</p></div> </div> </div> <div class="reply info"> <a class="comment-571018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571031" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jo_on" style="position: relative;"> <img src='https://userpic.codeforces.org/473527/avatar/f347e768dd5ae5b9.jpg'/> </a> <div><a href="/profile/jo_on" title="International Master jo_on" class="rated-user user-orange">jo_on</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571031" href="?#comment-571031" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571031" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="473527" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571031"> <div class="moveup"> <div class="ttypography"><p>Expected a matroid problem, as <a class="rated-user user-red" href="/profile/ko_osaga" title="International Grandmaster ko_osaga">ko_osaga</a> took matroid class last semester XD</p></div> </div> </div> <div class="reply info"> <a class="comment-571031 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571031 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571031"> <li> <div class="comment"> <table class="comment-table" commentId="571033" commentParentId="571031"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 08:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571033" href="?#comment-571033" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571031" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571033" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571033"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/team/65651">matroid fan club!</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571033 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571033 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571033"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571040" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PouyaNavid" style="position: relative;"> <img src='https://userpic.codeforces.org/670316/avatar/c42e949ea38011da.jpg'/> </a> <div><a href="/profile/PouyaNavid" title="Master PouyaNavid" class="rated-user user-orange">PouyaNavid</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 09:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571040" href="?#comment-571040" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571040" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="670316" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571040"> <div class="moveup"> <div class="ttypography"><p>Hack Test for D <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a></p><p>4 1 10 51 60 2 20 44 52 3 40 43 45 42 45 50 50</p></div> </div> </div> <div class="reply info"> <a class="comment-571040 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571040 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571040"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571088" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hazyknight" style="position: relative;"> <img src='https://userpic.codeforces.org/537474/avatar/e2c88ee4c2562699.jpg'/> </a> <div><a href="/profile/Hazyknight" title="International Grandmaster Hazyknight" class="rated-user user-red">Hazyknight</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 13:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571088" href="?#comment-571088" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="571088" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="571088" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="537474" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571088"> <div class="moveup"> <div class="ttypography"><p>Actually, Problem G can be solved easily by matroid intersection. Consider two matroid M1(S,I),M2(S,I), S is the set of wall, M1 is a graph matroid , M2 is a matroid which any black cell has at least to side without wall. Code: <a href="https://codeforces.com/contest/1284/submission/68215804">https://codeforces.com/contest/1284/submission/68215804</a></p></div> </div> </div> <div class="reply info"> <a class="comment-571088 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571088 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571088"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571128" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amstan" style="position: relative;"> <img src='https://userpic.codeforces.org/734003/avatar/344c500da9a98a7f.jpg'/> </a> <div><a href="/profile/amstan" title="Expert amstan" class="rated-user user-blue">amstan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 15:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571128" href="?#comment-571128" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571128" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="734003" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571128"> <div class="moveup"> <div class="ttypography"><p>Is there anyone who solved D using coordinate compression and prefix sum ? If so, could you please share your submission.</p></div> </div> </div> <div class="reply info"> <a class="comment-571128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571128"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571138" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HaoxuanXIE" style="position: relative;"> <img src='https://userpic.codeforces.org/1234114/avatar/fa4b56dfead7992e.jpg'/> </a> <div><a href="/profile/HaoxuanXIE" title="Expert HaoxuanXIE" class="rated-user user-blue">HaoxuanXIE</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571138" href="?#comment-571138" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571138" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1234114" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571138"> <div class="moveup"> <div class="ttypography"><p>Why does D need to check in two directions? If I check in one direction, I get wrong answer at 9th point. But I think it is appropriate to check in only one direction.</p></div> </div> </div> <div class="reply info"> <a class="comment-571138 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571138 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571138"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571145" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheeLooser" style="position: relative;"> <img src='https://userpic.codeforces.org/448032/avatar/d5dcfa8c5dbd255f.jpg'/> </a> <div><a href="/profile/TheeLooser" title="Expert TheeLooser" class="rated-user user-blue">TheeLooser</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 16:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571145" href="?#comment-571145" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571145" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="448032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-571145"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> may as well check how many visits were made to <a href="https://codeforces.com/problemset/problem/1146/H">this</a> page and later to <a href="https://codeforces.com/blog/entry/66639">this</a> page in contest time</p></div> </div> </div> <div class="reply info"> <a class="comment-571145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571145"> <li> <div class="comment"> <table class="comment-table" commentId="571459" commentParentId="571145"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/05/2020 22:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571459" href="?#comment-571459" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571145" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571459" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571459"> <div class="moveup"> <div class="ttypography"><p>How does that problem help?</p></div> </div> </div> <div class="reply info"> <a class="comment-571459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571459"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571509" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Petr" style="position: relative;"> <img src='https://userpic.codeforces.org/664/avatar/a113c1791cdcd2e1.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Petr" title="Legendary Grandmaster Petr" class="rated-user user-legendary"><span class="legendary-user-first-letter">P</span>etr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 01:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571509" href="?#comment-571509" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571509" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="664" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571509"> <div class="moveup"> <div class="ttypography"><p>Re: &quot;Hopefully, the first 80 tests were good enough for the contest.&quot;</p><p>My <a href="https://codeforces.com/contest/1284/submission/68208450">random solution</a> fails on test 87 :) Great job making the tests indeed!</p></div> </div> </div> <div class="reply info"> <a class="comment-571509 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571509 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571509"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571522" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MubtasimShahriar" style="position: relative;"> <img src='https://userpic.codeforces.org/756984/avatar/9113baa4abf04299.jpg'/> </a> <div><a href="/profile/MubtasimShahriar" title="Pupil MubtasimShahriar" class="rated-user user-green">MubtasimShahriar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 05:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571522" href="?#comment-571522" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571522" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756984" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-571522"> <div class="moveup"> <div class="ttypography"><p>In Problem D, why does this solution not work? My Solutions is this.</p><p>Sort lectures according to their start-ending time in both venue, Then decide every lecture if it intersects with others in their own venue.</p><p>If there is at least one lecture that make difference in intersecting in both venue, then Subset can not be made. So the answer is no. If every problem either intersects in both venue or does not intersect in both venue then answer is yes. Here is my implementation <a href="/contest/1284/submission/68294866" title="Submission 68294866 by MubtasimShahriar">68294866</a></p><p>Please someone enlighten me where I am misunderstanding.</p></div> </div> </div> <div class="reply info"> <a class="comment-571522 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571522 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571522"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571546" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SLIMSHADYNICK" style="position: relative;"> <img src='https://userpic.codeforces.org/598862/avatar/7629f1b29f0fe807.jpg'/> </a> <div><a href="/profile/SLIMSHADYNICK" title="Candidate Master SLIMSHADYNICK" class="rated-user user-violet">SLIMSHADYNICK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/06/2020 09:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571546" href="?#comment-571546" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571546" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-13" data-commentUserId="598862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-571546"> <div class="moveup"> <div class="ttypography"><p>In problem D, I got wrong answer on test case 14. Can somebody please help.</p></div> </div> </div> <div class="reply info"> <a class="comment-571546 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571546 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571546"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572491" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ftiasch" style="position: relative;"> <img src='https://userpic.codeforces.org/506/avatar/c52be21fbeb4a450.jpg'/> </a> <div><a href="/profile/ftiasch" title="International Grandmaster ftiasch" class="rated-user user-red">ftiasch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/11/2020 00:01">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572491" href="?#comment-572491" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572491" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="506" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-572491"> <div class="moveup"> <div class="ttypography"><p>2020 begins with two matroid problems. XD</p><p>btw, Challenge in Problem F is called Strong Basis Exchange as in <a href="https://math.mit.edu/~goemans/18438F09/lec11.pdf">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-572491 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572491 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572491"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572780" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Akash79" style="position: relative;"> <img src='https://userpic.codeforces.org/776725/avatar/700a28ac96121584.jpg'/> </a> <div><a href="/profile/Akash79" title="Expert Akash79" class="rated-user user-blue">Akash79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 16:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572780" href="?#comment-572780" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572780" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="776725" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572780"> <div class="moveup"> <div class="ttypography"><p>I am not able to understand problem B's solution.. can anyone please help me out..??</p></div> </div> </div> <div class="reply info"> <a class="comment-572780 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572780 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572780"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572849" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 17:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572849" href="?#comment-572849" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="572849" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="572849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572849"> <div class="moveup"> <div class="ttypography"><p>Why don't we have to consider the case when there's some period intersecting in A and not intersecting in B? Doesn't that mean that sometimes our code will say 'YES' but the answer is 'NO'. Why? <a href="/contest/1284/problem/D" title="Hello 2020">1284D - New Year and Conference</a>. EDIT: Ok, I just didn't notice the part of the code where he does the same thing but reversed.</p></div> </div> </div> <div class="reply info"> <a class="comment-572849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572849"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="572863" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Meiji" style="position: relative;"> <img src='https://userpic.codeforces.org/1357275/avatar/fbf247adb5d34383.jpg'/> </a> <div><a href="/profile/Meiji" title="Expert Meiji" class="rated-user user-blue">Meiji</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/12/2020 18:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-572863" href="?#comment-572863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="572863" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-572863"> <div class="moveup"> <div class="ttypography"><p>What is the hash approach for the problem D?</p></div> </div> </div> <div class="reply info"> <a class="comment-572863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-572863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-572863"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="576477" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anaksoleh" style="position: relative;"> <img src='https://userpic.codeforces.org/1170460/avatar/27d790d7abbbd3d9.jpg'/> </a> <div><a href="/profile/anaksoleh" title="Newbie anaksoleh" class="rated-user user-gray">anaksoleh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/30/2020 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-576477" href="?#comment-576477" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="576477" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170460" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-576477"> <div class="moveup"> <div class="ttypography"><p>there is a proof for C solution ?</p></div> </div> </div> <div class="reply info"> <a class="comment-576477 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-576477 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-576477"> <li> <div class="comment"> <table class="comment-table" commentId="673042" commentParentId="576477"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/XORring-Samurai" style="position: relative;"> <img src='https://userpic.codeforces.org/1384228/avatar/d0258d5ed6604923.jpg'/> </a> <div><a href="/profile/XORring-Samurai" title="Candidate Master XORring-Samurai" class="rated-user user-violet">XORring-Samurai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/02/2020 09:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-673042" href="?#comment-673042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-576477" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="673042" 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="673042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1384228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-673042"> <div class="moveup"> <div class="ttypography"><p>Here is something, that I could think of.</p><p>For each permutation, we have the same $$$r-l$$$. This value varies from $$$0$$$ to $$$n-1$$$ for all $$$n$$$. Now let us consider $$$r-l=d$$$, as a general case. </p><p>For each $$$n$$$, we have $$$n-d$$$ pairs of $$$[l, r]$$$, where $$$r-l=d$$$. Also for all numbers from $$$1$$$ to $$$n$$$, we have $$$n-d$$$ pairs of type $$$[i, j]$$$ such that $$$j-i=d$$$. </p><p>For a segment to be framed, all the other places for each $$$[l, r]$$$ must be occupied by each integer from $$$[i, j]$$$. Therefore, we have $$$d+1$$$ numbers to be arranged in this interval $$$[l, r]$$$ and $$$n-d-1$$$ to be arranged in $$$[1, l-1]$$$ and $$$[r+1, n]$$$. This can be done in $$$(d+1)! * (n-d-1)!$$$ ways. </p><p>But we have $$$n-d$$$ pairs of $$$[l, r]$$$ and $$$n-d$$$ pairs of $$$[i, j]$$$, each of which can occupy this segment. Therefore the answer becomes summation over all $$$d$$$ from $$$0$$$ to $$$n-1$$$: $$$ans = ans + (n-d) * (n-d) * (d+1)! * (n-d-1)!$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-673042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-673042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-673042"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606852" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ThakurSaab" style="position: relative;"> <img src='https://userpic.codeforces.org/1267713/avatar/7c6c4d7b58cddb96.jpg'/> </a> <div><a href="/profile/ThakurSaab" title="Expert ThakurSaab" class="rated-user user-blue">ThakurSaab</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 17:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606852" href="?#comment-606852" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606852" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1267713" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606852"> <div class="moveup"> <div class="ttypography"><p>In problem C , do we consider that the numbers inside a particular segment [l,r] could be different such that, max-min = r-l</p></div> </div> </div> <div class="reply info"> <a class="comment-606852 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606852 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606852"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="689589" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 07:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689589" href="?#comment-689589" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689589" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689589"> <div class="moveup"> <div class="ttypography"><p>In Problem D I added elements in the segment tree in the decreasing order of eai and then I queried for the previous range if the min of the ls and the maxr intersect with the particular index of a I am addding . I am getting a WA at Test Case 7 for this submission.</p><p>This is my submission link: <a href="https://codeforces.com/contest/1284/submission/91535000">https://codeforces.com/contest/1284/submission/91535000</a></p><p>Can somebody help me with this solution where I went wrong? </p><p>Or is there anyway I can look at the whole testcase then please reply here about how can I do that?</p></div> </div> </div> <div class="reply info"> <a class="comment-689589 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689589 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689589"> <li> <div class="comment"> <table class="comment-table" commentId="689595" commentParentId="689589"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mr.Doap" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mr.Doap" title="Expert Mr.Doap" class="rated-user user-blue">Mr.Doap</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2020 08:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689595" href="?#comment-689595" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-689589" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689595" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="763686" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689595"> <div class="moveup"> <div class="ttypography"><p>Never Mind I made a silly typo in the cmp2 function.</p></div> </div> </div> <div class="reply info"> <a class="comment-689595 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689595 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689595"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="722358" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tanishq_code_c" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tanishq_code_c" title="Expert tanishq_code_c" class="rated-user user-blue">tanishq_code_c</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/17/2020 17:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-722358" href="?#comment-722358" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="722358" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1484322" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-722358"> <div class="moveup"> <div class="ttypography"><p>Hi, I am not able to understand the editorial for problem C. can anyone break it down in easy way please ? </p></div> </div> </div> <div class="reply info"> <a class="comment-722358 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-722358 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-722358"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="736312" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheOneYouWant" style="position: relative;"> <img src='https://userpic.codeforces.org/628619/avatar/c785428bde285c3.jpg'/> </a> <div><a href="/profile/TheOneYouWant" title="Master TheOneYouWant" class="rated-user user-orange">TheOneYouWant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/23/2020 05:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-736312" href="?#comment-736312" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="736312" class="CommentVoteFrame" data-commentRating="91" data-commentUserId="628619" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+91</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-736312"> <div class="moveup"> <div class="ttypography"><p>Hello, this seems to be broken (perhaps a sign of how the year 2020 has been so far)</p></div> </div> </div> <div class="reply info"> <a class="comment-736312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-736312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-736312"> <li> <div class="comment"> <table class="comment-table" commentId="737407" commentParentId="736312"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/27/2020 09:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-737407" href="?#comment-737407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-736312" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="737407" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-737407"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a> please take a look, thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-737407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-737407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-737407"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741444" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/butterflies" style="position: relative;"> <img src='https://userpic.codeforces.org/1651561/avatar/33dfc9c16e5795ad.jpg'/> </a> <div><a href="/profile/butterflies" title="Specialist butterflies" class="rated-user user-cyan">butterflies</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741444" href="?#comment-741444" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="741444" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="741444" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1651561" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741444"> <div class="moveup"> <div class="ttypography"><p>This question relates to <a href="https://codeforces.com/contest/1284/problem/B">problem B</a>. I have a question with the second example input. Here is the input:</p> <pre><code>3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 </code></pre><p>I believe all arrays have an ascent. In the first array, the pair $$$(i, j) = (3, 4)$$$ works. ($$$a_3 = 0, a_4 = 2.$$$) In the second array, the pair $$$(i, j) = (1, 2)$$$ works. ($$$a_1 = 6, a_2 = 9.$$$) In the third array, the pair $$$(i,j) = (1, 2)$$$ works. ($$$a_1 = 1, a_2 = 6.$$$)</p><p>Thus, shouldn't all pairs of arrays in this case work? There are $$$9$$$ such pairs, but the answer to this should be $$$7.$$$ What is wrong with my reasoning here?</p></div> </div> </div> <div class="reply info"> <a class="comment-741444 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741444 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741444"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741445" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/beetroot" style="position: relative;"> <img src='https://userpic.codeforces.org/1503072/avatar/6668dbf5be4e4495.jpg'/> </a> <div><a href="/profile/beetroot" title="Expert beetroot" class="rated-user user-blue">beetroot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 05:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741445" href="?#comment-741445" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741445" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1503072" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741445"> <div class="moveup"> <div class="ttypography"><p>Editorials that didn't age well...</p></div> </div> </div> <div class="reply info"> <a class="comment-741445 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741445 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741445"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="741475" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ko_osaga" style="position: relative;"> <img src='https://userpic.codeforces.org/210765/avatar/90b51bd6ebd11e79.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ko_osaga" title="Legendary Grandmaster ko_osaga" class="rated-user user-legendary"><span class="legendary-user-first-letter">k</span>o_osaga</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/01/2021 07:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-741475" href="?#comment-741475" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="741475" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="210765" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-741475"> <div class="moveup"> <div class="ttypography"><p>Sorry for the issue with editorials. I think there is a timeout issue from Polygon. Since I can't resolve it, I will just rewrite it as a PDF form and upload here.</p></div> </div> </div> <div class="reply info"> <a class="comment-741475 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-741475 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-741475"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="797067" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/YPK" style="position: relative;"> <img src='https://userpic.codeforces.org/1489397/avatar/bd42de2aca7084dd.jpg'/> </a> <div><a href="/profile/YPK" title="Master YPK" class="rated-user user-orange">YPK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/29/2021 11:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-797067" href="?#comment-797067" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="797067" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="797067" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1489397" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-797067"> <div class="moveup"> <div class="ttypography"><p>Weak test cases for D. Consider the following test case </p> <pre><code>3 1 3 1 2 4 6 4 5 5 7 2 3 </code></pre><p>My accepted solution gives YES but the answer is NO.</p></div> </div> </div> <div class="reply info"> <a class="comment-797067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-797067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-797067"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="891199" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav04" style="position: relative;"> <img src='https://userpic.codeforces.org/2093148/avatar/b05253879beed26d.jpg'/> </a> <div><a href="/profile/abhinav04" title="Specialist abhinav04" class="rated-user user-cyan">abhinav04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/27/2022 11:56">19 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-891199" href="?#comment-891199" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="891199" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="2093148" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-891199"> <div class="moveup"> <div class="ttypography"><p>In case someone needs help with problem B, this might help.</p> <div class="spoiler"><b class="spoiler-title">submission</b><div class="spoiler-content" style="display: none;"><p><a href="https://codeforces.com/contest/1284/submission/147841447">https://codeforces.com/contest/1284/submission/147841447</a></p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-891199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-891199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-891199"> </ul> </div> <br/> <div id="editBox-78289" 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 firstPreview78289 = true; var lastPreviewContent78289 = ''; 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=78289] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=78289] 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-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-73334").click(function () { $.post("/data/topic/vote", {topicId: 73334, _tta: Codeforces.tta(), topicRevisionId: 213163, 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:27:29</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81288aad58e60057',t:'MTY5NjcwNjg0OS42NzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1285A
1285
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>Сегодня Мезо решил сыграть в игру. Зома, главный герой в этой игре, изначально находится в позиции $$$x = 0$$$. Мезо посылает $$$n$$$ команд Зоме. Возможны два типа команд:</p><ul> <li> 'L' (Влево) устанавливает позицию $$$x: =x - 1$$$; </li><li> 'R' (Вправо) устанавливает позицию $$$x: =x + 1$$$. </li></ul><p>К сожалению, контроллер Мезо иногда не срабатывает. Некоторые команды отправляются успешно, а некоторые нет. Если команда не отправлена, то позиция $$$x$$$ не меняется, и Мезо просто переходит к следующей команде.</p><p>Например, если Мезо отправляет команды «<span class="tex-font-style-tt">LRLR</span>», тогда возможны следующие исходы (подчеркнутые команды отправлены успешно):</p><ul> <li> «<span class="tex-font-style-tt"><span class="tex-font-style-underline">LRLR</span></span>» — Зома перемещается влево, вправо, опять влево и наконец вправо, заканчивая в позиции $$$0$$$; </li><li> «<span class="tex-font-style-tt">LRLR</span>» — ни одна команда не отправлена, поэтому Зома никуда не двигается и заканчивает снова в позиции $$$0$$$; </li><li> «<span class="tex-font-style-tt"><span class="tex-font-style-underline">L</span>R<span class="tex-font-style-underline">L</span>R</span>» — Зома перемещается влево, затем опять влево и закнчивает в позиции $$$-2$$$. </li></ul><p>Мезо не знает заранее, какие команды будут отправлены успешно. Поэтому он хочет узнать, сколько существует различных позиций таких, что Зома может закончить в них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ $$$(1 \le n \le 10^5)$$$ — количество команд, посылаемых Мезо.</p><p>Во второй строке записана строка $$$s$$$ из $$$n$$$ команд, каждая либо 'L' (Влево), либо 'R' (Вправо).</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 LRLR </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><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="16ed01d78041963fcda8b04319b23018"/> <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="6b270e40adc0aa833019bf8c41433cff258f90d7"/> <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='16ed01d78041963fcda8b04319b23018'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1285%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='16ed01d78041963fcda8b04319b23018'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1285">Codeforces Round 613 (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='16ed01d78041963fcda8b04319b23018'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1285/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='16ed01d78041963fcda8b04319b23018'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="512926"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='16ed01d78041963fcda8b04319b23018'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="512926"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72938" title="Codeforces Round #613 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10281" resourceName="Codeforces Round #613 (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/72950" title="Codeforces Round #613 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10286" resourceName="Codeforces Round #613 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1285">Задачи</a></li> <li><a href="/contest/1285/submit">Отослать</a></li> <li><a href="/contest/1285/my">Мои посылки</a></li> <li><a href="/contest/1285/status">Статус</a></li> <li><a href="/contest/1285/hacks">Взломы</a></li> <li><a href="/contest/1285/room/1">Комната</a></li> <li><a href="/contest/1285/standings">Положение</a></li> <li><a href="/contest/1285/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2b10de6031f327c82828ba9c42a5f1749929e549"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Сегодня Мезо решил сыграть в игру. Зома, главный герой в этой игре, изначально находится в позиции $$$x = 0$$$. Мезо посылает $$$n$$$ команд Зоме. Возможны два типа команд:</p><ul> <li> 'L' (Влево) устанавливает позицию $$$x: =x - 1$$$; </li><li> 'R' (Вправо) устанавливает позицию $$$x: =x + 1$$$. </li></ul><p>К сожалению, контроллер Мезо иногда не срабатывает. Некоторые команды отправляются успешно, а некоторые нет. Если команда не отправлена, то позиция $$$x$$$ не меняется, и Мезо просто переходит к следующей команде.</p><p>Например, если Мезо отправляет команды «<span class="tex-font-style-tt">LRLR</span>», тогда возможны следующие исходы (подчеркнутые команды отправлены успешно):</p><ul> <li> «<span class="tex-font-style-tt"><span class="tex-font-style-underline">LRLR</span></span>» — Зома перемещается влево, вправо, опять влево и наконец вправо, заканчивая в позиции $$$0$$$; </li><li> «<span class="tex-font-style-tt">LRLR</span>» — ни одна команда не отправлена, поэтому Зома никуда не двигается и заканчивает снова в позиции $$$0$$$; </li><li> «<span class="tex-font-style-tt"><span class="tex-font-style-underline">L</span>R<span class="tex-font-style-underline">L</span>R</span>» — Зома перемещается влево, затем опять влево и закнчивает в позиции $$$-2$$$. </li></ul><p>Мезо не знает заранее, какие команды будут отправлены успешно. Поэтому он хочет узнать, сколько существует различных позиций таких, что Зома может закончить в них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ $$$(1 \le n \le 10^5)$$$ — количество команд, посылаемых Мезо.</p><p>Во второй строке записана строка $$$s$$$ из $$$n$$$ команд, каждая либо 'L' (Влево), либо 'R' (Вправо).</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 LRLR </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере Зома может закончить в любой позиции от $$$-2$$$ до $$$2$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:54: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:'81249339889e9d70',t:'MTY5NjY2NTI1Ni4wOTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1285B
1285
B
ru
B. Вкусные покупки
<div class="problem-statement"><div class="header"><div class="title">B. Вкусные покупки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Сегодня Яссер и Адель пошли в магазин за пирожными. На полке в магазине стоят $$$n$$$ типов пирожных, пронумерованные от $$$1$$$ до $$$n$$$. Количество пирожных каждого типа бесконечно. Определим вкус $$$i$$$-го пирожного некоторой величиной $$$a_i$$$, которая является целым числом. В магазине есть как вкусные пирожные, так и неприятные, поэтому данная величина может быть положительной, нулем или отрицательной.</p><p>Яссер, разумеется, хочет попробовать их все, поэтому он купит ровно по одному пирожному каждого типа.</p><p>Адель, с другой стороны, выберет некоторый отрезок $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$, который содержит не все пирожные (он не может выбрать $$$[l, r] = [1, n]$$$) и купит ровно по одному пирожному каждого из типов $$$l, l + 1, \dots, r$$$.</p><p>После этого они сравнят суммарный вкус купленных ими пирожных. Яссер будет счастлив, если суммарный вкус пирожных, которые он купил, <span class="tex-font-style-bf">строго</span> больше, чем суммарный вкус пирожных, которые купил Адель <span class="tex-font-style-bf">вне зависимости от выбора Адель</span>.</p><p>Например, пусть вкус пирожных будет $$$[7, 4, -1]$$$. Яссер купит все, суммарный вкус будет равен $$$7 + 4 - 1 = 10$$$. Адель может выбрать отрезки $$$[7], [4], [-1], [7, 4]$$$ или $$$[4, -1]$$$, суммарный вкус будет равен $$$7, 4, -1, 11$$$ и $$$3$$$, соответственно. Адель может выбрать отрезок с суммарным вкусом $$$11$$$, и раз $$$10$$$ не строго больше $$$11$$$, то Яссер не будет счастлив :(</p><p>Узнайте, будет ли Яссер счастлив после похода в магазин.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В каждом тесте содержится несколько наборов входных данных. В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных. Затем следует описание наборов входных данных.</p><p>В первой строке каждого набора входных данных записано одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$).</p><p>Во второй строке каждого набора входных данных записаны $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), где $$$a_i$$$ является вкусом $$$i$$$-го типа пирожного.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">YES</span>», если суммарный вкус пирожных, которые купил Яссер, <span class="tex-font-style-bf">строго</span> больше, чем суммарный вкус пирожных, которые купил Адель <span class="tex-font-style-bf">вне зависимости от выбора Адель</span>. В противном случае выведите «<span class="tex-font-style-tt">NO</span>».</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 2 3 4 3 7 4 -1 3 5 -5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере суммарный вкус любого отрезка, который может выбрать Адель, меньше, чем суммарный вкус всех пирожных.</p><p>Во втором примере Адель выберет отрезок $$$[1, 2]$$$ с суммарным вкусом $$$11$$$, что не меньше, чем суммарный вкус всех пирожных, который равен $$$10$$$.</p><p>В третьем примере, Адель может выбрать отрезок $$$[3, 3]$$$ c суммарным вкусом $$$5$$$. Обратите внимание, что вкус пирожных у Яссера тоже равен $$$5$$$, поэтому в данном случае суммарный вкус пирожных, которые купил Яссер, не строго больше, чем суммарный вкус пирожных, которые купил Адель.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="d22f0ecba663246fc282297d714a56b4"/> <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="6b270e40adc0aa833019bf8c41433cff258f90d7"/> <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='d22f0ecba663246fc282297d714a56b4'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1285%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='d22f0ecba663246fc282297d714a56b4'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1285">Codeforces Round 613 (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='d22f0ecba663246fc282297d714a56b4'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1285/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='d22f0ecba663246fc282297d714a56b4'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="512927"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d22f0ecba663246fc282297d714a56b4'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="512927"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72938" title="Codeforces Round #613 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10281" resourceName="Codeforces Round #613 (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/72950" title="Codeforces Round #613 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10286" resourceName="Codeforces Round #613 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1285">Задачи</a></li> <li><a href="/contest/1285/submit">Отослать</a></li> <li><a href="/contest/1285/my">Мои посылки</a></li> <li><a href="/contest/1285/status">Статус</a></li> <li><a href="/contest/1285/hacks">Взломы</a></li> <li><a href="/contest/1285/room/1">Комната</a></li> <li><a href="/contest/1285/standings">Положение</a></li> <li><a href="/contest/1285/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_944ce837857e66be553762a3172b3a79e05f5648"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Вкусные покупки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Сегодня Яссер и Адель пошли в магазин за пирожными. На полке в магазине стоят $$$n$$$ типов пирожных, пронумерованные от $$$1$$$ до $$$n$$$. Количество пирожных каждого типа бесконечно. Определим вкус $$$i$$$-го пирожного некоторой величиной $$$a_i$$$, которая является целым числом. В магазине есть как вкусные пирожные, так и неприятные, поэтому данная величина может быть положительной, нулем или отрицательной.</p><p>Яссер, разумеется, хочет попробовать их все, поэтому он купит ровно по одному пирожному каждого типа.</p><p>Адель, с другой стороны, выберет некоторый отрезок $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$, который содержит не все пирожные (он не может выбрать $$$[l, r] = [1, n]$$$) и купит ровно по одному пирожному каждого из типов $$$l, l + 1, \dots, r$$$.</p><p>После этого они сравнят суммарный вкус купленных ими пирожных. Яссер будет счастлив, если суммарный вкус пирожных, которые он купил, <span class="tex-font-style-bf">строго</span> больше, чем суммарный вкус пирожных, которые купил Адель <span class="tex-font-style-bf">вне зависимости от выбора Адель</span>.</p><p>Например, пусть вкус пирожных будет $$$[7, 4, -1]$$$. Яссер купит все, суммарный вкус будет равен $$$7 + 4 - 1 = 10$$$. Адель может выбрать отрезки $$$[7], [4], [-1], [7, 4]$$$ или $$$[4, -1]$$$, суммарный вкус будет равен $$$7, 4, -1, 11$$$ и $$$3$$$, соответственно. Адель может выбрать отрезок с суммарным вкусом $$$11$$$, и раз $$$10$$$ не строго больше $$$11$$$, то Яссер не будет счастлив :(</p><p>Узнайте, будет ли Яссер счастлив после похода в магазин.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В каждом тесте содержится несколько наборов входных данных. В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных. Затем следует описание наборов входных данных.</p><p>В первой строке каждого набора входных данных записано одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$).</p><p>Во второй строке каждого набора входных данных записаны $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), где $$$a_i$$$ является вкусом $$$i$$$-го типа пирожного.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">YES</span>», если суммарный вкус пирожных, которые купил Яссер, <span class="tex-font-style-bf">строго</span> больше, чем суммарный вкус пирожных, которые купил Адель <span class="tex-font-style-bf">вне зависимости от выбора Адель</span>. В противном случае выведите «<span class="tex-font-style-tt">NO</span>».</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 2 3 4 3 7 4 -1 3 5 -5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере суммарный вкус любого отрезка, который может выбрать Адель, меньше, чем суммарный вкус всех пирожных.</p><p>Во втором примере Адель выберет отрезок $$$[1, 2]$$$ с суммарным вкусом $$$11$$$, что не меньше, чем суммарный вкус всех пирожных, который равен $$$10$$$.</p><p>В третьем примере, Адель может выбрать отрезок $$$[3, 3]$$$ c суммарным вкусом $$$5$$$. Обратите внимание, что вкус пирожных у Яссера тоже равен $$$5$$$, поэтому в данном случае суммарный вкус пирожных, которые купил Яссер, не строго больше, чем суммарный вкус пирожных, которые купил Адель.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'812493422ab29d39',t:'MTY5NjY2NTI1Ny40NDgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1300"]
1285C
1285
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>Сегодня Осама вручил Фади целое число $$$X$$$, а Фади стало интересно, какое минимальное значение может принимать $$$max(a, b)$$$ таких, что $$$LCM(a, b)$$$ равен $$$X$$$. $$$a$$$ и $$$b$$$ должны быть положительными целыми числами.</p><p>$$$LCM(a, b)$$$ — это наименьшее положительное целое число, которое делится и на $$$a$$$, и на $$$b$$$. Например, $$$LCM(6, 8) = 24$$$, $$$LCM(4, 12) = 12$$$, $$$LCM(2, 3) = 6$$$.</p><p>Разумеется, Фади сразу нашел ответ. Сможете ли вы найти любую такую пару прямо как Фади?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой и единственной строке записано одно целое число $$$X$$$ ($$$1 \le X \le 10^{12}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых положительных числа, $$$a$$$ и $$$b$$$, такие, что значение $$$max(a, b)$$$ минимально возможное, а $$$LCM(a, b)$$$ равен $$$X$$$. Если существует несколько возможных пар, то выведите любую из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="91e675164166ea1538fb5f7b0797feb7"/> <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="6b270e40adc0aa833019bf8c41433cff258f90d7"/> <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='91e675164166ea1538fb5f7b0797feb7'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1285%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='91e675164166ea1538fb5f7b0797feb7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1285">Codeforces Round 613 (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='91e675164166ea1538fb5f7b0797feb7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1285/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='91e675164166ea1538fb5f7b0797feb7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="512928"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='91e675164166ea1538fb5f7b0797feb7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="512928"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72938" title="Codeforces Round #613 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10281" resourceName="Codeforces Round #613 (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/72950" title="Codeforces Round #613 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10286" resourceName="Codeforces Round #613 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1285">Задачи</a></li> <li><a href="/contest/1285/submit">Отослать</a></li> <li><a href="/contest/1285/my">Мои посылки</a></li> <li><a href="/contest/1285/status">Статус</a></li> <li><a href="/contest/1285/hacks">Взломы</a></li> <li><a href="/contest/1285/room/1">Комната</a></li> <li><a href="/contest/1285/standings">Положение</a></li> <li><a href="/contest/1285/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7ca5fbe10138bf0fddbd0a10b6c4e312056cd001"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Сегодня Осама вручил Фади целое число $$$X$$$, а Фади стало интересно, какое минимальное значение может принимать $$$max(a, b)$$$ таких, что $$$LCM(a, b)$$$ равен $$$X$$$. $$$a$$$ и $$$b$$$ должны быть положительными целыми числами.</p><p>$$$LCM(a, b)$$$ — это наименьшее положительное целое число, которое делится и на $$$a$$$, и на $$$b$$$. Например, $$$LCM(6, 8) = 24$$$, $$$LCM(4, 12) = 12$$$, $$$LCM(2, 3) = 6$$$.</p><p>Разумеется, Фади сразу нашел ответ. Сможете ли вы найти любую такую пару прямо как Фади?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой и единственной строке записано одно целое число $$$X$$$ ($$$1 \le X \le 10^{12}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых положительных числа, $$$a$$$ и $$$b$$$, такие, что значение $$$max(a, b)$$$ минимально возможное, а $$$LCM(a, b)$$$ равен $$$X$$$. Если существует несколько возможных пар, то выведите любую из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'8124934abdfd3a8f',t:'MTY5NjY2NTI1OC44NzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1400"]
1285D
1285
D
ru
D. Dr. Evil Underscores
<div class="problem-statement"><div class="header"><div class="title">D. Dr. Evil Underscores</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Сегодня Бакри в качестве дружеского подарка вручил Бадави $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ и дал ему задачку выбрать такой $$$X$$$, что $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ принимает минимальное возможное значение, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>.</p><p>Бадави, как обычно, ленится, поэтому вы решили помочь ему и найти минимальное возможное значение $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1\le n \le 10^5$$$).</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное возможное значение $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно выбрать $$$X = 3$$$.</p><p>Во втором примере можно выбрать $$$X = 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="74d7f294b1a3e75175a349f646db071f"/> <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="6b270e40adc0aa833019bf8c41433cff258f90d7"/> <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='74d7f294b1a3e75175a349f646db071f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1285%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='74d7f294b1a3e75175a349f646db071f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1285">Codeforces Round 613 (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='74d7f294b1a3e75175a349f646db071f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1285/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Разделяй и властвуй"> разделяй и властвуй </span> </div> <div class="roundbox borderTopRound 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='74d7f294b1a3e75175a349f646db071f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="512929"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='74d7f294b1a3e75175a349f646db071f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="512929"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72938" title="Codeforces Round #613 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10281" resourceName="Codeforces Round #613 (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/72950" title="Codeforces Round #613 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10286" resourceName="Codeforces Round #613 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1285">Задачи</a></li> <li><a href="/contest/1285/submit">Отослать</a></li> <li><a href="/contest/1285/my">Мои посылки</a></li> <li><a href="/contest/1285/status">Статус</a></li> <li><a href="/contest/1285/hacks">Взломы</a></li> <li><a href="/contest/1285/room/1">Комната</a></li> <li><a href="/contest/1285/standings">Положение</a></li> <li><a href="/contest/1285/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b14f75f3057e3733cb2076c8c3e5c6fd8e54cae9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Dr. Evil Underscores</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Сегодня Бакри в качестве дружеского подарка вручил Бадави $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ и дал ему задачку выбрать такой $$$X$$$, что $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ принимает минимальное возможное значение, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>.</p><p>Бадави, как обычно, ленится, поэтому вы решили помочь ему и найти минимальное возможное значение $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1\le n \le 10^5$$$).</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное возможное значение $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно выбрать $$$X = 3$$$.</p><p>Во втором примере можно выбрать $$$X = 5$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'812493538ec10058',t:'MTY5NjY2NTI2MC4yNDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\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", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\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\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1900"]
1285E
1285
E
ru
E. Удали один отрезок
<div class="problem-statement"><div class="header"><div class="title">E. Удали один отрезок</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На координатной прямой $$$Ox$$$ заданы $$$n$$$ отрезков $$$[l_1, r_1]$$$, $$$[l_2, r_2]$$$, ..., $$$[l_n, r_n]$$$. Отрезок $$$[l, r]$$$ покрывает все точки от $$$l$$$ до $$$r$$$ включительно, то есть такие $$$x$$$, что $$$l \le x \le r$$$.</p><p>Отрезки могут располагаться <span class="tex-font-style-it">произвольным</span> образом  — вкладываться друг в друга, совпадать и т.п. Отрезки могут вырождаться в точку, то есть допустимо, что $$$l_i=r_i$$$.</p><p><span class="tex-font-style-it">Объединением</span> набора отрезков называется такой минимальный набор отрезков, который покрывает в точности тот же набор точек, что и заданный набор. Например:</p><ul> <li> если $$$n=3$$$ и отрезки имеют вид $$$[3, 6]$$$, $$$[100, 100]$$$, $$$[5, 8]$$$, то их объединение состоит из $$$2$$$ отрезков: $$$[3, 8]$$$ и $$$[100, 100]$$$; </li><li> если $$$n=5$$$ и отрезки имеют вид $$$[1, 2]$$$, $$$[2, 3]$$$, $$$[4, 5]$$$, $$$[4, 6]$$$, $$$[6, 6]$$$ то их объединение состоит из $$$2$$$ отрезков: $$$[1, 3]$$$ и $$$[4, 6]$$$. </li></ul><p>Очевидно, что объединение — это набор непересекающихся отрезков.</p><p>Требуется удалить ровно один отрезок из заданных $$$n$$$ таким образом, чтобы количество отрезков в объединении оставшихся $$$n-1$$$ было наибольшим.</p><p>Например, если $$$n=4$$$ и отрезки имеют вид $$$[1, 4]$$$, $$$[2, 3]$$$, $$$[3, 6]$$$, $$$[5, 7]$$$, то:</p><ul> <li> если из набора удалить первый отрезок, то останутся отрезки $$$[2, 3]$$$, $$$[3, 6]$$$, $$$[5, 7]$$$, объединение которых состоит из $$$1$$$ отрезка; </li><li> если из набора удалить второй отрезок, то останутся отрезки $$$[1, 4]$$$, $$$[3, 6]$$$, $$$[5, 7]$$$, объединение которых состоит из $$$1$$$ отрезка; </li><li> если из набора удалить третий отрезок, то останутся отрезки $$$[1, 4]$$$, $$$[2, 3]$$$, $$$[5, 7]$$$, объединение которых состоит из $$$2$$$ отрезков; </li><li> если из набора удалить четвертый отрезок, то останутся отрезки $$$[1, 4]$$$, $$$[2, 3]$$$, $$$[3, 6]$$$, объединение которых состоит из $$$1$$$ отрезка. </li></ul><p>Таким образом, в примере выше надо обязательно удалять третий отрезок, чтобы получить ответ $$$2$$$.</p><p>Напишите программу, которая найдет наибольшее количество отрезков, которые получатся в объединении $$$n-1$$$ оставшегося, если можно удалить любой из заданных $$$n$$$ отрезков.</p><p><span class="tex-font-style-it">Обратите внимание, что если в заданном наборе есть несколько одинаковых отрезков, то удалить вы всё-равно можете ровно один из них. То есть набор отрезков после удаления одного будет содержать ровно $$$n-1$$$ отрезок.</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора содержит целое число $$$n$$$ ($$$2 \le n \le 2\cdot10^5$$$) — количество отрезков в заданном наборе. Далее в $$$n$$$ строках заданы сами отрезки парами целых чисел $$$l_i$$$, $$$r_i$$$ ($$$-10^9 \le l_i \le r_i \le 10^9$$$), где $$$l_i$$$ и $$$r_i$$$ — координаты левого и правого конца $$$i$$$-го отрезка, соответственно.</p><p>Отрезки заданы в произвольном порядке.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам во входных данных не превосходит $$$2\cdot10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ чисел — ответы на заданные $$$t$$$ наборов входных данных в порядке их следования в тесте. Ответ равен максимальному количеству отрезков в объединении $$$n-1$$$ отрезка из $$$n$$$ заданных, если допускается удалить один любой отрезок.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 5 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="bd216b820751660e08f6f5f5bb5be1a9"/> <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="6b270e40adc0aa833019bf8c41433cff258f90d7"/> <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='bd216b820751660e08f6f5f5bb5be1a9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1285%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='bd216b820751660e08f6f5f5bb5be1a9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1285">Codeforces Round 613 (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='bd216b820751660e08f6f5f5bb5be1a9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1285/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='bd216b820751660e08f6f5f5bb5be1a9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="512930"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bd216b820751660e08f6f5f5bb5be1a9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="512930"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72938" title="Codeforces Round #613 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10281" resourceName="Codeforces Round #613 (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/72950" title="Codeforces Round #613 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10286" resourceName="Codeforces Round #613 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1285">Задачи</a></li> <li><a href="/contest/1285/submit">Отослать</a></li> <li><a href="/contest/1285/my">Мои посылки</a></li> <li><a href="/contest/1285/status">Статус</a></li> <li><a href="/contest/1285/hacks">Взломы</a></li> <li><a href="/contest/1285/room/1">Комната</a></li> <li><a href="/contest/1285/standings">Положение</a></li> <li><a href="/contest/1285/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b4335ed15fc1e75e3da4bcfb34cad69f47fcf726"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Удали один отрезок</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На координатной прямой $$$Ox$$$ заданы $$$n$$$ отрезков $$$[l_1, r_1]$$$, $$$[l_2, r_2]$$$, ..., $$$[l_n, r_n]$$$. Отрезок $$$[l, r]$$$ покрывает все точки от $$$l$$$ до $$$r$$$ включительно, то есть такие $$$x$$$, что $$$l \le x \le r$$$.</p><p>Отрезки могут располагаться <span class="tex-font-style-it">произвольным</span> образом  — вкладываться друг в друга, совпадать и т.п. Отрезки могут вырождаться в точку, то есть допустимо, что $$$l_i=r_i$$$.</p><p><span class="tex-font-style-it">Объединением</span> набора отрезков называется такой минимальный набор отрезков, который покрывает в точности тот же набор точек, что и заданный набор. Например:</p><ul> <li> если $$$n=3$$$ и отрезки имеют вид $$$[3, 6]$$$, $$$[100, 100]$$$, $$$[5, 8]$$$, то их объединение состоит из $$$2$$$ отрезков: $$$[3, 8]$$$ и $$$[100, 100]$$$; </li><li> если $$$n=5$$$ и отрезки имеют вид $$$[1, 2]$$$, $$$[2, 3]$$$, $$$[4, 5]$$$, $$$[4, 6]$$$, $$$[6, 6]$$$ то их объединение состоит из $$$2$$$ отрезков: $$$[1, 3]$$$ и $$$[4, 6]$$$. </li></ul><p>Очевидно, что объединение — это набор непересекающихся отрезков.</p><p>Требуется удалить ровно один отрезок из заданных $$$n$$$ таким образом, чтобы количество отрезков в объединении оставшихся $$$n-1$$$ было наибольшим.</p><p>Например, если $$$n=4$$$ и отрезки имеют вид $$$[1, 4]$$$, $$$[2, 3]$$$, $$$[3, 6]$$$, $$$[5, 7]$$$, то:</p><ul> <li> если из набора удалить первый отрезок, то останутся отрезки $$$[2, 3]$$$, $$$[3, 6]$$$, $$$[5, 7]$$$, объединение которых состоит из $$$1$$$ отрезка; </li><li> если из набора удалить второй отрезок, то останутся отрезки $$$[1, 4]$$$, $$$[3, 6]$$$, $$$[5, 7]$$$, объединение которых состоит из $$$1$$$ отрезка; </li><li> если из набора удалить третий отрезок, то останутся отрезки $$$[1, 4]$$$, $$$[2, 3]$$$, $$$[5, 7]$$$, объединение которых состоит из $$$2$$$ отрезков; </li><li> если из набора удалить четвертый отрезок, то останутся отрезки $$$[1, 4]$$$, $$$[2, 3]$$$, $$$[3, 6]$$$, объединение которых состоит из $$$1$$$ отрезка. </li></ul><p>Таким образом, в примере выше надо обязательно удалять третий отрезок, чтобы получить ответ $$$2$$$.</p><p>Напишите программу, которая найдет наибольшее количество отрезков, которые получатся в объединении $$$n-1$$$ оставшегося, если можно удалить любой из заданных $$$n$$$ отрезков.</p><p><span class="tex-font-style-it">Обратите внимание, что если в заданном наборе есть несколько одинаковых отрезков, то удалить вы всё-равно можете ровно один из них. То есть набор отрезков после удаления одного будет содержать ровно $$$n-1$$$ отрезок.</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора содержит целое число $$$n$$$ ($$$2 \le n \le 2\cdot10^5$$$) — количество отрезков в заданном наборе. Далее в $$$n$$$ строках заданы сами отрезки парами целых чисел $$$l_i$$$, $$$r_i$$$ ($$$-10^9 \le l_i \le r_i \le 10^9$$$), где $$$l_i$$$ и $$$r_i$$$ — координаты левого и правого конца $$$i$$$-го отрезка, соответственно.</p><p>Отрезки заданы в произвольном порядке.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам во входных данных не превосходит $$$2\cdot10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ чисел — ответы на заданные $$$t$$$ наборов входных данных в порядке их следования в тесте. Ответ равен максимальному количеству отрезков в объединении $$$n-1$$$ отрезка из $$$n$$$ заданных, если допускается удалить один любой отрезок.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 5 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54:21</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'8124935c49641667',t:'MTY5NjY2NTI2MS42MjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2300"]
1285F
1285
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>Дан массив $$$a$$$, состоящий из $$$n$$$ целых чисел, найдите:</p><p>$$$$$$\max\limits_{1 \le i &lt; j \le n} LCM(a_i,a_j),$$$$$$</p><p>где $$$LCM(x, y)$$$ — это наименьшее положительное целое число, которое делится и на $$$x$$$, и на $$$y$$$. Например, $$$LCM(6, 8) = 24$$$, $$$LCM(4, 12) = 12$$$, $$$LCM(2, 3) = 6$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — количество элементов в массиве $$$a$$$.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — элементы массива $$$a$$$.</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 13 35 77 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1001</pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 2 4 8 16 32 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 32</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="f3bb42a6066f62aaa32dca771afae7c9"/> <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="6b270e40adc0aa833019bf8c41433cff258f90d7"/> <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='f3bb42a6066f62aaa32dca771afae7c9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1285%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='f3bb42a6066f62aaa32dca771afae7c9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1285">Codeforces Round 613 (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='f3bb42a6066f62aaa32dca771afae7c9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1285/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2900 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f3bb42a6066f62aaa32dca771afae7c9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="512931"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f3bb42a6066f62aaa32dca771afae7c9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="512931"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72938" title="Codeforces Round #613 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10281" resourceName="Codeforces Round #613 (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/72950" title="Codeforces Round #613 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10286" resourceName="Codeforces Round #613 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1285">Задачи</a></li> <li><a href="/contest/1285/submit">Отослать</a></li> <li><a href="/contest/1285/my">Мои посылки</a></li> <li><a href="/contest/1285/status">Статус</a></li> <li><a href="/contest/1285/hacks">Взломы</a></li> <li><a href="/contest/1285/room/1">Комната</a></li> <li><a href="/contest/1285/standings">Положение</a></li> <li><a href="/contest/1285/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_90f4c8764bc2fcfe62785b86b1d4ec4b0185b95d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Дан массив $$$a$$$, состоящий из $$$n$$$ целых чисел, найдите:</p><p>$$$$$$\max\limits_{1 \le i &lt; j \le n} LCM(a_i,a_j),$$$$$$</p><p>где $$$LCM(x, y)$$$ — это наименьшее положительное целое число, которое делится и на $$$x$$$, и на $$$y$$$. Например, $$$LCM(6, 8) = 24$$$, $$$LCM(4, 12) = 12$$$, $$$LCM(2, 3) = 6$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — количество элементов в массиве $$$a$$$.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — элементы массива $$$a$$$.</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 13 35 77 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1001</pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 2 4 8 16 32 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 32</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:54: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:'81249364dd991610',t:'MTY5NjY2NTI2My4wMDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2900"]
1286A
1286
A
ru
A. Гирлянда
<div class="problem-statement"><div class="header"><div class="title">A. Гирлянда</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вадим очень любит наряжать новогоднюю ёлку, поэтому ему подарили невероятно красивую гирлянду. Она состоит из $$$n$$$ лампочек, расположенных в ряд. На каждой лампочке написано число от $$$1$$$ до $$$n$$$, причем все числа различны и шли в произвольном порядке. Пока Вадим решал задачи, его домашний Карась снял с гирлянды некоторые лампочки. Теперь Вадим хочет вернуть их на место.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/c87ff8b17badad0f05d83d783c8343a0a00725a6.png" style="max-width: 100.0%;max-height: 100.0%;"/></center><p>Вадим хочет повесить все лампочки обратно на гирлянду. Он считает <span class="tex-font-style-it">сложностью</span> гирлянды количество пар соседних лампочек, на которых написаны числа разной четности (то есть имеющие разные остатки при делении на $$$2$$$). Например, сложность гирлянды <span class="tex-font-style-tt">1 4 2 3 5</span> равна $$$2$$$, а сложность гирлянды <span class="tex-font-style-tt">1 3 5 7 6 4 2</span>, равна $$$1$$$.</p><p>Никто не любит сложности, поэтому Вадим хочет минимизировать количество таких пар. Найдите способ повесить снятые лампочки на гирлянду, чтобы минимизировать ее сложность.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — количество лампочек в гирлянде.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$p_1,\ p_2,\ \ldots,\ p_n$$$ ($$$0 \le p_i \le n$$$) — номер $$$i$$$-й лампочки или $$$0$$$, если Карась ее снял.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — минимальную <span class="tex-font-style-it">сложность</span> гирлянды. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 0 5 0 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 1 0 0 5 0 0 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>В первом примере надо расставить лампочки как <span class="tex-font-style-tt">1 5 4 2 3</span>. В этом случае сложность будет равна 2, так как рядом расположены пары лампочек $$$(5, 4)$$$ и $$$(2, 3)$$$.</p><p>Во втором примере один из правильных ответов <span class="tex-font-style-tt">1 7 3 5 6 4 2</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="b10548d6ee539d65cf7b523d3a11ffa1"/> <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="b76268a612690f667c95bf2c0d8485a22e1d8aa6"/> <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='b10548d6ee539d65cf7b523d3a11ffa1'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1286%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='b10548d6ee539d65cf7b523d3a11ffa1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1286">Codeforces Round 612 (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='b10548d6ee539d65cf7b523d3a11ffa1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1286/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='b10548d6ee539d65cf7b523d3a11ffa1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509639"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b10548d6ee539d65cf7b523d3a11ffa1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509639"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10240:10241" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10252" resourceName="Codeforces Round #612 - 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/1286">Задачи</a></li> <li><a href="/contest/1286/submit">Отослать</a></li> <li><a href="/contest/1286/my">Мои посылки</a></li> <li><a href="/contest/1286/status">Статус</a></li> <li><a href="/contest/1286/hacks">Взломы</a></li> <li><a href="/contest/1286/room/1">Комната</a></li> <li><a href="/contest/1286/standings">Положение</a></li> <li><a href="/contest/1286/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_38ea2581beffcadbd40c112e662ed9986078a9db"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Гирлянда</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вадим очень любит наряжать новогоднюю ёлку, поэтому ему подарили невероятно красивую гирлянду. Она состоит из $$$n$$$ лампочек, расположенных в ряд. На каждой лампочке написано число от $$$1$$$ до $$$n$$$, причем все числа различны и шли в произвольном порядке. Пока Вадим решал задачи, его домашний Карась снял с гирлянды некоторые лампочки. Теперь Вадим хочет вернуть их на место.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/c87ff8b17badad0f05d83d783c8343a0a00725a6.png" style="max-width: 100.0%;max-height: 100.0%;" /></center><p>Вадим хочет повесить все лампочки обратно на гирлянду. Он считает <span class="tex-font-style-it">сложностью</span> гирлянды количество пар соседних лампочек, на которых написаны числа разной четности (то есть имеющие разные остатки при делении на $$$2$$$). Например, сложность гирлянды <span class="tex-font-style-tt">1 4 2 3 5</span> равна $$$2$$$, а сложность гирлянды <span class="tex-font-style-tt">1 3 5 7 6 4 2</span>, равна $$$1$$$.</p><p>Никто не любит сложности, поэтому Вадим хочет минимизировать количество таких пар. Найдите способ повесить снятые лампочки на гирлянду, чтобы минимизировать ее сложность.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — количество лампочек в гирлянде.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$p_1,\ p_2,\ \ldots,\ p_n$$$ ($$$0 \le p_i \le n$$$) — номер $$$i$$$-й лампочки или $$$0$$$, если Карась ее снял.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — минимальную <span class="tex-font-style-it">сложность</span> гирлянды. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 0 5 0 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 1 0 0 5 0 0 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>В первом примере надо расставить лампочки как <span class="tex-font-style-tt">1 5 4 2 3</span>. В этом случае сложность будет равна 2, так как рядом расположены пары лампочек $$$(5, 4)$$$ и $$$(2, 3)$$$.</p><p>Во втором примере один из правильных ответов <span class="tex-font-style-tt">1 7 3 5 6 4 2</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:54: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:'8124936d996b13ba',t:'MTY5NjY2NTI2NC40NzEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1800"]
1286B
1286
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>Евлампию подарили корневое дерево, вершины которого пронумерованы от $$$1$$$ до $$$n$$$. В каждой $$$i$$$-й вершине написано число $$$a_i$$$. Евлампий посчитал для каждой вершины $$$i$$$ величину $$$c_i$$$ — количество вершин $$$j$$$ в поддереве вершины $$$i$$$, для которых $$$a_j &lt; a_i$$$.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/0578b7af7f1f0aec057b6485b22c80a6adb3e4c8.png" style="max-width: 100.0%;max-height: 100.0%;"/>Иллюстрация ко второму примеру, первым написано $$$a_i$$$, а в скобках написано $$$c_i$$$</center><p>После нового года Евлампий не смог вспомнить, каким был его подарок! Он помнит дерево и значения $$$c_i$$$, однако совсем забыл, какие числа $$$a_i$$$ были написаны в вершинах. Помогите ему восстановить исходные числа!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится целое число $$$n$$$ $$$(1 \leq n \leq 2000)$$$ — количество вершин в дереве.</p><p>Далее в $$$n$$$ строках идёт описание вершин дерева: в $$$i$$$-й строке находятся два целых числа $$$p_i$$$ и $$$c_i$$$ ($$$0 \leq p_i \leq n$$$; $$$0 \leq c_i \leq n-1$$$), где $$$p_i$$$ — номер родителя вершины $$$i$$$ или $$$0$$$ для корня дерева, а $$$c_i$$$ — количество вершин $$$j$$$ в поддереве вершины $$$i$$$, для которых $$$a_j &lt; a_i$$$.</p><p>Гарантируется, что значения $$$p_i$$$ задают некоторое корневое дерево из $$$n$$$ вершин.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если решение существует, то в первой строке выведите «<span class="tex-font-style-tt">YES</span>», а во второй строке выведите $$$n$$$ чисел $$$a_i$$$ $$$(1 \leq a_i \leq {10}^{9})$$$ — искомые числа, которые были записаны в вершинах дерева. Если решений несколько, выведите любое из них. Можно показать, что если решение существует, то также существует решение, где все $$$a_i$$$ лежат от $$$1$$$ до $$$10^9$$$.</p><p>Если же решения не существует, то выведите «<span class="tex-font-style-tt">NO</span>».</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 0 0 2 2 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 1 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 1 1 3 2 1 3 0 2 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 2 3 2 1 2 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="48391aa868e0f93a795a315b78fe723d"/> <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="b76268a612690f667c95bf2c0d8485a22e1d8aa6"/> <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='48391aa868e0f93a795a315b78fe723d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1286%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='48391aa868e0f93a795a315b78fe723d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1286">Codeforces Round 612 (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='48391aa868e0f93a795a315b78fe723d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1286/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='48391aa868e0f93a795a315b78fe723d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509640"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='48391aa868e0f93a795a315b78fe723d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509640"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10240:10241" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10252" resourceName="Codeforces Round #612 - 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/1286">Задачи</a></li> <li><a href="/contest/1286/submit">Отослать</a></li> <li><a href="/contest/1286/my">Мои посылки</a></li> <li><a href="/contest/1286/status">Статус</a></li> <li><a href="/contest/1286/hacks">Взломы</a></li> <li><a href="/contest/1286/room/1">Комната</a></li> <li><a href="/contest/1286/standings">Положение</a></li> <li><a href="/contest/1286/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e80c76afb0e366bd2fdef7595cda73ed45fd547e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Евлампию подарили корневое дерево, вершины которого пронумерованы от $$$1$$$ до $$$n$$$. В каждой $$$i$$$-й вершине написано число $$$a_i$$$. Евлампий посчитал для каждой вершины $$$i$$$ величину $$$c_i$$$ — количество вершин $$$j$$$ в поддереве вершины $$$i$$$, для которых $$$a_j &lt; a_i$$$.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/0578b7af7f1f0aec057b6485b22c80a6adb3e4c8.png" style="max-width: 100.0%;max-height: 100.0%;" />Иллюстрация ко второму примеру, первым написано $$$a_i$$$, а в скобках написано $$$c_i$$$</center><p>После нового года Евлампий не смог вспомнить, каким был его подарок! Он помнит дерево и значения $$$c_i$$$, однако совсем забыл, какие числа $$$a_i$$$ были написаны в вершинах. Помогите ему восстановить исходные числа!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится целое число $$$n$$$ $$$(1 \leq n \leq 2000)$$$ — количество вершин в дереве.</p><p>Далее в $$$n$$$ строках идёт описание вершин дерева: в $$$i$$$-й строке находятся два целых числа $$$p_i$$$ и $$$c_i$$$ ($$$0 \leq p_i \leq n$$$; $$$0 \leq c_i \leq n-1$$$), где $$$p_i$$$ — номер родителя вершины $$$i$$$ или $$$0$$$ для корня дерева, а $$$c_i$$$ — количество вершин $$$j$$$ в поддереве вершины $$$i$$$, для которых $$$a_j &lt; a_i$$$.</p><p>Гарантируется, что значения $$$p_i$$$ задают некоторое корневое дерево из $$$n$$$ вершин.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если решение существует, то в первой строке выведите «<span class="tex-font-style-tt">YES</span>», а во второй строке выведите $$$n$$$ чисел $$$a_i$$$ $$$(1 \leq a_i \leq {10}^{9})$$$ — искомые числа, которые были записаны в вершинах дерева. Если решений несколько, выведите любое из них. Можно показать, что если решение существует, то также существует решение, где все $$$a_i$$$ лежат от $$$1$$$ до $$$10^9$$$.</p><p>Если же решения не существует, то выведите «<span class="tex-font-style-tt">NO</span>».</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 0 0 2 2 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 1 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 1 1 3 2 1 3 0 2 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 2 3 2 1 2 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54:25</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'81249376abec9d4c',t:'MTY5NjY2NTI2NS45NjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1800"]
1286C1
1286
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>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Эта задача отличается от сложной версии только ограничением на суммарную длину ответов</span></p><p><span class="tex-font-style-bf">Это интерактивная задача</span>.</p><p>Веня приехал на экскурсию в дурдом, в котором санитары играют с пациентами в следующую игру: санитары загадывают строку $$$s$$$ длины $$$n$$$, состоящую только из строчных букв английского алфавита. Пациент может делать запросы двух типов: </p><ul> <li> <span class="tex-font-style-tt">? l r</span> — запросить все подстроки $$$s[l..r]$$$. При этом в ответе все подстроки будут перемешаны, а в каждой из подстрок будут перемешаны буквы. </li><li> <span class="tex-font-style-tt">! s</span> — сделать предположение о загаданной строке. Этот запрос нужно сделать ровно один раз, после него игра завершается. Если строка угадана, то пациент побеждает, а иначе проигрывает. </li></ul><p>Пациенту разрешено сделать <span class="tex-font-style-bf">не более $$$3$$$ запросов</span> первого типа. Чтобы игра была не так утомительна для санитаров, существует следующее ограничение: суммарно на запросы первого типа должно быть возвращено не более $$$(n+1)^2$$$ подстрок.</p><p>Помогите пациенту выиграть и выбраться из дурдома!</p><p>После запроса второго типа ваша программа должна немедленно завершиться. В случае, если ваша программа неверно угадает строку или превысит заданные ограничения на количество запросов или количество возвращенных подстрок, она получит вердикт <span class="tex-font-style-tt">Неправильный ответ</span>.</p><p>Обратите внимание, что в каждом тесте строка фиксирована и не меняется в ходе игры. Иными словами, интерактор не адаптивен.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая и единственная строка содержит число $$$n$$$ ($$$1 \le n \le 100$$$) — длину загадываемой строки.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Вы начинаете своё взаимодействие, считав $$$n$$$.</p><p>Для того, чтобы задать вопрос о подстроке с $$$l$$$ по $$$r$$$ включительно ($$$1 \le l \le r \le n$$$) выведите в отдельной строке</p><p><span class="tex-font-style-tt">? l r</span></p><p>В ответ вы получите все подстроки строки $$$s[l..r]$$$ в случайном порядке, каждую ровно один раз. В каждой из подстрок будут случайным образом перемешаны буквы. </p><p>В случае, если вы сделаете некорректный запрос, зададите более $$$3$$$ запросов данного типа, или в результате заданных запросов Вам будет возвращено суммарно более $$$(n+1)^2$$$ подстрок, то ваше решение получит вердикт <span class="tex-font-style-bf">Неправильный ответ</span>.</p><p>Для того, чтобы сделать предположение о загаданной строке $$$s$$$ выведите в отдельной строке</p><p><span class="tex-font-style-tt">! s</span></p><p>После вывода каждого запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> fflush(stdout) или cout.flush() в C++; </li><li> System.out.flush() в Java; </li><li> flush(output) в Pascal; </li><li> stdout.flush() в Python; </li><li> смотрите документацию для других языков. </li></ul><p>Если вы получили строку <span class="tex-font-style-tt">-</span> (дефис) в качестве ответа на какой-либо запрос, то вам надо завершить программу штатным образом с кодом возврата 0 (например, сделав <span class="tex-font-style-tt">exit(0)</span>). Это означает, что интерактор зафиксировал ошибку в протоколе или поведении программы. Если вы не завершите в этом случае программу штатным образом с кодом возврата 0, то можете получить любой неуспешный вердикт.</p><p><span class="tex-font-style-bf">Формат взломов</span></p><p>Для взломов используйте следующий формат:</p><p>В первой строке должно быть единственное число $$$n$$$ ($$$1 \le n \le 100$$$) — длина загадываемой строки.</p><p>Во второй строке выведите строку $$$s$$$ — сама загадываемая строка.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 a aa a cb b c c</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 2 ? 3 4 ? 4 4 ! aabc</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="197e4a4b689a4c97de6091180454b729"/> <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="b76268a612690f667c95bf2c0d8485a22e1d8aa6"/> <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='197e4a4b689a4c97de6091180454b729'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1286%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='197e4a4b689a4c97de6091180454b729'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1286">Codeforces Round 612 (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='197e4a4b689a4c97de6091180454b729'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1286/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='197e4a4b689a4c97de6091180454b729'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509641"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='197e4a4b689a4c97de6091180454b729'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509641"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10240:10241" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10252" resourceName="Codeforces Round #612 - 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/1286">Задачи</a></li> <li><a href="/contest/1286/submit">Отослать</a></li> <li><a href="/contest/1286/my">Мои посылки</a></li> <li><a href="/contest/1286/status">Статус</a></li> <li><a href="/contest/1286/hacks">Взломы</a></li> <li><a href="/contest/1286/room/1">Комната</a></li> <li><a href="/contest/1286/standings">Положение</a></li> <li><a href="/contest/1286/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_49e579b4c95a0ce862e01250bd77aca4e297c3ae"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Эта задача отличается от сложной версии только ограничением на суммарную длину ответов</span></p><p><span class="tex-font-style-bf">Это интерактивная задача</span>.</p><p>Веня приехал на экскурсию в дурдом, в котором санитары играют с пациентами в следующую игру: санитары загадывают строку $$$s$$$ длины $$$n$$$, состоящую только из строчных букв английского алфавита. Пациент может делать запросы двух типов: </p><ul> <li> <span class="tex-font-style-tt">? l r</span> — запросить все подстроки $$$s[l..r]$$$. При этом в ответе все подстроки будут перемешаны, а в каждой из подстрок будут перемешаны буквы. </li><li> <span class="tex-font-style-tt">! s</span> — сделать предположение о загаданной строке. Этот запрос нужно сделать ровно один раз, после него игра завершается. Если строка угадана, то пациент побеждает, а иначе проигрывает. </li></ul><p>Пациенту разрешено сделать <span class="tex-font-style-bf">не более $$$3$$$ запросов</span> первого типа. Чтобы игра была не так утомительна для санитаров, существует следующее ограничение: суммарно на запросы первого типа должно быть возвращено не более $$$(n+1)^2$$$ подстрок.</p><p>Помогите пациенту выиграть и выбраться из дурдома!</p><p>После запроса второго типа ваша программа должна немедленно завершиться. В случае, если ваша программа неверно угадает строку или превысит заданные ограничения на количество запросов или количество возвращенных подстрок, она получит вердикт <span class="tex-font-style-tt">Неправильный ответ</span>.</p><p>Обратите внимание, что в каждом тесте строка фиксирована и не меняется в ходе игры. Иными словами, интерактор не адаптивен.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая и единственная строка содержит число $$$n$$$ ($$$1 \le n \le 100$$$) — длину загадываемой строки.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Вы начинаете своё взаимодействие, считав $$$n$$$.</p><p>Для того, чтобы задать вопрос о подстроке с $$$l$$$ по $$$r$$$ включительно ($$$1 \le l \le r \le n$$$) выведите в отдельной строке</p><p><span class="tex-font-style-tt">? l r</span></p><p>В ответ вы получите все подстроки строки $$$s[l..r]$$$ в случайном порядке, каждую ровно один раз. В каждой из подстрок будут случайным образом перемешаны буквы. </p><p>В случае, если вы сделаете некорректный запрос, зададите более $$$3$$$ запросов данного типа, или в результате заданных запросов Вам будет возвращено суммарно более $$$(n+1)^2$$$ подстрок, то ваше решение получит вердикт <span class="tex-font-style-bf">Неправильный ответ</span>.</p><p>Для того, чтобы сделать предположение о загаданной строке $$$s$$$ выведите в отдельной строке</p><p><span class="tex-font-style-tt">! s</span></p><p>После вывода каждого запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> fflush(stdout) или cout.flush() в C++; </li><li> System.out.flush() в Java; </li><li> flush(output) в Pascal; </li><li> stdout.flush() в Python; </li><li> смотрите документацию для других языков. </li></ul><p>Если вы получили строку <span class="tex-font-style-tt">-</span> (дефис) в качестве ответа на какой-либо запрос, то вам надо завершить программу штатным образом с кодом возврата 0 (например, сделав <span class="tex-font-style-tt">exit(0)</span>). Это означает, что интерактор зафиксировал ошибку в протоколе или поведении программы. Если вы не завершите в этом случае программу штатным образом с кодом возврата 0, то можете получить любой неуспешный вердикт.</p><p><span class="tex-font-style-bf">Формат взломов</span></p><p>Для взломов используйте следующий формат:</p><p>В первой строке должно быть единственное число $$$n$$$ ($$$1 \le n \le 100$$$) — длина загадываемой строки.</p><p>Во второй строке выведите строку $$$s$$$ — сама загадываемая строка.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 a aa a cb b c c</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 2 ? 3 4 ? 4 4 ! aabc</pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:54:27</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'8124937ffbbb9d84',t:'MTY5NjY2NTI2Ny40MDMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2400"]
1286C2
1286
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>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Эта задача отличается от простой версии только ограничением на суммарную длину ответов</span></p><p><span class="tex-font-style-bf">Это интерактивная задача</span>.</p><p>Веня приехал на экскурсию в дурдом, в котором санитары играют с пациентами в следующую игру: санитары загадывают строку $$$s$$$ длины $$$n$$$, состоящую только из строчных букв английского алфавита. Пациент может делать запросы двух типов: </p><ul> <li> <span class="tex-font-style-tt">? l r</span> — запросить все подстроки $$$s[l..r]$$$. При этом в ответе все подстроки будут перемешаны, а в каждой из подстрок будут перемешаны буквы. </li><li> <span class="tex-font-style-tt">! s</span> — сделать предположение о загаданной строке. Этот запрос нужно сделать ровно один раз, после него игра завершается. Если строка угадана, то пациент побеждает, а иначе проигрывает. </li></ul><p>Пациенту разрешено сделать <span class="tex-font-style-bf">не более $$$3$$$ запросов</span> первого типа. Чтобы игра была не так утомительна для санитаров, существует следующее ограничение: суммарно на запросы первого типа должно быть возвращено не более $$$\left\lceil 0.777(n+1)^2 \right\rceil$$$ подстрок ($$$\lceil x \rceil$$$ — округление вверх числа $$$x$$$).</p><p>Помогите пациенту выиграть и выбраться из дурдома!</p><p>После запроса второго типа ваша программа должна немедленно завершиться. В случае, если ваша программа неверно угадает строку или превысит заданные ограничения на количество запросов или количество возвращенных подстрок, она получит вердикт <span class="tex-font-style-tt">Неправильный ответ</span>.</p><p>Обратите внимание, что в каждом тесте строка фиксирована и не меняется в ходе игры. Иными словами, интерактор не адаптивен.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая и единственная строка содержит число $$$n$$$ ($$$1 \le n \le 100$$$) — длину загадываемой строки.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Вы начинаете своё взаимодействие, считав $$$n$$$.</p><p>Для того, чтобы задать вопрос о подстроке с $$$l$$$ по $$$r$$$ включительно ($$$1 \le l \le r \le n$$$) выведите в отдельной строке</p><p><span class="tex-font-style-tt">? l r</span></p><p>В ответ вы получите все подстроки строки $$$s[l..r]$$$ в случайном порядке, каждую ровно один раз. В каждой из подстрок будут случайным образом перемешаны буквы. </p><p>В случае, если вы сделаете некорректный запрос, зададите более $$$3$$$ запросов данного типа, или в результате заданных запросов Вам будет возвращено суммарно более $$$\left\lceil 0.777(n+1)^2 \right\rceil$$$ подстрок, то ваше решение получит вердикт <span class="tex-font-style-bf">Неправильный ответ</span>.</p><p>Для того, чтобы сделать предположение о загаданной строке $$$s$$$ выведите в отдельной строке</p><p><span class="tex-font-style-tt">! s</span></p><p>После вывода каждого запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> fflush(stdout) или cout.flush() в C++; </li><li> System.out.flush() в Java; </li><li> flush(output) в Pascal; </li><li> stdout.flush() в Python; </li><li> смотрите документацию для других языков. </li></ul><p>Если вы получили строку <span class="tex-font-style-tt">-</span> (дефис) в качестве ответа на какой-либо запрос, то вам надо завершить программу штатным образом с кодом возврата 0 (например, сделав <span class="tex-font-style-tt">exit(0)</span>). Это означает, что интерактор зафиксировал ошибку в протоколе или поведении программы. Если вы не завершите в этом случае программу штатным образом с кодом возврата 0, то можете получить любой неуспешный вердикт.</p><p><span class="tex-font-style-bf">Формат взломов.</span></p><p>Для взломов используйте следующий формат:</p><p>В первой строке должно быть единственное число $$$n$$$ ($$$1 \le n \le 100$$$) — длина загадываемой строки.</p><p>Во второй строке выведите строку $$$s$$$ – сама загадываемая строка.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 a aa a cb b c c</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 2 ? 3 4 ? 4 4 ! aabc</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="c288de2481ac8b09422c32abd3dcc2d9"/> <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="b76268a612690f667c95bf2c0d8485a22e1d8aa6"/> <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='c288de2481ac8b09422c32abd3dcc2d9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1286%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='c288de2481ac8b09422c32abd3dcc2d9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1286">Codeforces Round 612 (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='c288de2481ac8b09422c32abd3dcc2d9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1286/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы"> хэши </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c288de2481ac8b09422c32abd3dcc2d9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509642"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c288de2481ac8b09422c32abd3dcc2d9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509642"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10240:10241" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10252" resourceName="Codeforces Round #612 - 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/1286">Задачи</a></li> <li><a href="/contest/1286/submit">Отослать</a></li> <li><a href="/contest/1286/my">Мои посылки</a></li> <li><a href="/contest/1286/status">Статус</a></li> <li><a href="/contest/1286/hacks">Взломы</a></li> <li><a href="/contest/1286/room/1">Комната</a></li> <li><a href="/contest/1286/standings">Положение</a></li> <li><a href="/contest/1286/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d519b5269aaf0213253a6edea47cf7cc4b067ccb"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Эта задача отличается от простой версии только ограничением на суммарную длину ответов</span></p><p><span class="tex-font-style-bf">Это интерактивная задача</span>.</p><p>Веня приехал на экскурсию в дурдом, в котором санитары играют с пациентами в следующую игру: санитары загадывают строку $$$s$$$ длины $$$n$$$, состоящую только из строчных букв английского алфавита. Пациент может делать запросы двух типов: </p><ul> <li> <span class="tex-font-style-tt">? l r</span> — запросить все подстроки $$$s[l..r]$$$. При этом в ответе все подстроки будут перемешаны, а в каждой из подстрок будут перемешаны буквы. </li><li> <span class="tex-font-style-tt">! s</span> — сделать предположение о загаданной строке. Этот запрос нужно сделать ровно один раз, после него игра завершается. Если строка угадана, то пациент побеждает, а иначе проигрывает. </li></ul><p>Пациенту разрешено сделать <span class="tex-font-style-bf">не более $$$3$$$ запросов</span> первого типа. Чтобы игра была не так утомительна для санитаров, существует следующее ограничение: суммарно на запросы первого типа должно быть возвращено не более $$$\left\lceil 0.777(n+1)^2 \right\rceil$$$ подстрок ($$$\lceil x \rceil$$$ — округление вверх числа $$$x$$$).</p><p>Помогите пациенту выиграть и выбраться из дурдома!</p><p>После запроса второго типа ваша программа должна немедленно завершиться. В случае, если ваша программа неверно угадает строку или превысит заданные ограничения на количество запросов или количество возвращенных подстрок, она получит вердикт <span class="tex-font-style-tt">Неправильный ответ</span>.</p><p>Обратите внимание, что в каждом тесте строка фиксирована и не меняется в ходе игры. Иными словами, интерактор не адаптивен.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая и единственная строка содержит число $$$n$$$ ($$$1 \le n \le 100$$$) — длину загадываемой строки.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Вы начинаете своё взаимодействие, считав $$$n$$$.</p><p>Для того, чтобы задать вопрос о подстроке с $$$l$$$ по $$$r$$$ включительно ($$$1 \le l \le r \le n$$$) выведите в отдельной строке</p><p><span class="tex-font-style-tt">? l r</span></p><p>В ответ вы получите все подстроки строки $$$s[l..r]$$$ в случайном порядке, каждую ровно один раз. В каждой из подстрок будут случайным образом перемешаны буквы. </p><p>В случае, если вы сделаете некорректный запрос, зададите более $$$3$$$ запросов данного типа, или в результате заданных запросов Вам будет возвращено суммарно более $$$\left\lceil 0.777(n+1)^2 \right\rceil$$$ подстрок, то ваше решение получит вердикт <span class="tex-font-style-bf">Неправильный ответ</span>.</p><p>Для того, чтобы сделать предположение о загаданной строке $$$s$$$ выведите в отдельной строке</p><p><span class="tex-font-style-tt">! s</span></p><p>После вывода каждого запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> fflush(stdout) или cout.flush() в C++; </li><li> System.out.flush() в Java; </li><li> flush(output) в Pascal; </li><li> stdout.flush() в Python; </li><li> смотрите документацию для других языков. </li></ul><p>Если вы получили строку <span class="tex-font-style-tt">-</span> (дефис) в качестве ответа на какой-либо запрос, то вам надо завершить программу штатным образом с кодом возврата 0 (например, сделав <span class="tex-font-style-tt">exit(0)</span>). Это означает, что интерактор зафиксировал ошибку в протоколе или поведении программы. Если вы не завершите в этом случае программу штатным образом с кодом возврата 0, то можете получить любой неуспешный вердикт.</p><p><span class="tex-font-style-bf">Формат взломов.</span></p><p>Для взломов используйте следующий формат:</p><p>В первой строке должно быть единственное число $$$n$$$ ($$$1 \le n \le 100$$$) — длина загадываемой строки.</p><p>Во второй строке выведите строку $$$s$$$ – сама загадываемая строка.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 a aa a cb b c c</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 2 ? 3 4 ? 4 4 ! aabc</pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:54: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:'81249388fd7a3374',t:'MTY5NjY2NTI2OC43MzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0425\u044d\u0448\u0438, \u0445\u044d\u0448-\u0442\u0430\u0431\u043b\u0438\u0446\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0445\u044d\u0448\u0438", "*2800"]
1286D
1286
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$$$ труб c координатами $$$x_i$$$. В момент времени 0 из каждой трубки ЛЧК вылетает протон направо с вероятностью $$$p_i$$$ и с вероятностью $$$(1 - p_i)$$$ — влево. Протон $$$i$$$ разогнан до скорости $$$v_i$$$. Длительность эксперимента определяется как время до первого столкновения двух протонов. В случае, если столкновений не произойдет, длительность эксперимента полагается равной нулю.</p><p>Найдите математическое ожидание длительности эксперимента.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/8f71f247f9973aa84c688f02028df0fa69838ce5.png" style="max-width: 100.0%;max-height: 100.0%;"/>Иллюстрация к первому примеру</center></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ — количество труб ($$$1 \le n \le 10^5$$$). В следующих $$$n$$$ строках содержится по три целых числа $$$x_i$$$, $$$v_i$$$, $$$p_i$$$ — координата $$$i$$$-й трубы, скорость $$$i$$$-го протона, и вероятность вылета $$$i$$$-го протона вправо в процентах ($$$-10^9 \le x_i \le 10^9, 1 \le v \le 10^6, 0 \le p_i \le 100$$$). Гарантируется, что все $$$x_i$$$ различны и отсортированы в порядке возрастания.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Можно показать, что ответ всегда можно представить в виде дроби $$$P/Q$$$, где $$$P$$$ — целое число, а $$$Q$$$ — натуральное число, не кратное $$$998\,244\,353$$$. В таком случае выведите $$$P \cdot Q^{-1}$$$ по модулю $$$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> 2 1 1 100 3 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 7 10 0 9 4 86 14 5 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 6 4 50 11 25 50 13 16 50 15 8 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 150902884 </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="13adcff1ef10a1899e63393eca663562"/> <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="b76268a612690f667c95bf2c0d8485a22e1d8aa6"/> <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='13adcff1ef10a1899e63393eca663562'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1286%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='13adcff1ef10a1899e63393eca663562'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1286">Codeforces Round 612 (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='13adcff1ef10a1899e63393eca663562'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1286/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Произведение матриц, определитель, правило Крамера, системы линейных уравнений"> матрицы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др."> теория вероятностей </span> </div> <div class="roundbox borderTopRound 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='13adcff1ef10a1899e63393eca663562'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509643"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='13adcff1ef10a1899e63393eca663562'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509643"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10240:10241" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10252" resourceName="Codeforces Round #612 - 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/1286">Задачи</a></li> <li><a href="/contest/1286/submit">Отослать</a></li> <li><a href="/contest/1286/my">Мои посылки</a></li> <li><a href="/contest/1286/status">Статус</a></li> <li><a href="/contest/1286/hacks">Взломы</a></li> <li><a href="/contest/1286/room/1">Комната</a></li> <li><a href="/contest/1286/standings">Положение</a></li> <li><a href="/contest/1286/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ebd3831bc3614b14e97b89978a840a63f7573b7c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ труб c координатами $$$x_i$$$. В момент времени 0 из каждой трубки ЛЧК вылетает протон направо с вероятностью $$$p_i$$$ и с вероятностью $$$(1 - p_i)$$$ — влево. Протон $$$i$$$ разогнан до скорости $$$v_i$$$. Длительность эксперимента определяется как время до первого столкновения двух протонов. В случае, если столкновений не произойдет, длительность эксперимента полагается равной нулю.</p><p>Найдите математическое ожидание длительности эксперимента.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/8f71f247f9973aa84c688f02028df0fa69838ce5.png" style="max-width: 100.0%;max-height: 100.0%;" />Иллюстрация к первому примеру</center></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ — количество труб ($$$1 \le n \le 10^5$$$). В следующих $$$n$$$ строках содержится по три целых числа $$$x_i$$$, $$$v_i$$$, $$$p_i$$$ — координата $$$i$$$-й трубы, скорость $$$i$$$-го протона, и вероятность вылета $$$i$$$-го протона вправо в процентах ($$$-10^9 \le x_i \le 10^9, 1 \le v \le 10^6, 0 \le p_i \le 100$$$). Гарантируется, что все $$$x_i$$$ различны и отсортированы в порядке возрастания.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Можно показать, что ответ всегда можно представить в виде дроби $$$P/Q$$$, где $$$P$$$ — целое число, а $$$Q$$$ — натуральное число, не кратное $$$998\,244\,353$$$. В таком случае выведите $$$P \cdot Q^{-1}$$$ по модулю $$$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> 2 1 1 100 3 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 7 10 0 9 4 86 14 5 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 6 4 50 11 25 50 13 16 50 15 8 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 150902884 </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:54: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:'812493913c7c9d45',t:'MTY5NjY2NTI3MC4xNDMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u043c\u0430\u0442\u0440\u0438\u0446, \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044c, \u043f\u0440\u0430\u0432\u0438\u043b\u043e \u041a\u0440\u0430\u043c\u0435\u0440\u0430, \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0445 \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0439", "\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.", "\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"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043c\u0430\u0442\u0440\u0438\u0446\u044b", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*3100"]
1286E
1286
E
ru
E. Гончар Фёдор наносит ответный удар
<div class="problem-statement"><div class="header"><div class="title">E. Гончар Фёдор наносит ответный удар</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Феди есть строка $$$S$$$, изначально пустая, и массив $$$W$$$, тоже изначально пустой.</p><p>Феде по одному приходят $$$n$$$ запросов к этой строке и этому массиву. Запрос $$$i$$$ состоит из строчной буквы английского алфавита $$$c_i$$$ и целого неотрицательного числа $$$w_i$$$. К строке $$$S$$$ необходимо в конец приписать символ $$$c_i$$$, а к $$$W$$$ в конец добавить $$$w_i$$$. Ответом на запрос является сумма <span class="tex-font-style-it">подозрительностей</span> по всем подотрезкам $$$[L, \ R]$$$ массива $$$W$$$ $$$(1 \leq L \leq R \leq i)$$$.</p><p>Определим <span class="tex-font-style-it">подозрительность</span> подотрезка следующим образом: если подстрока $$$S$$$, соответствующая этому подотрезку (то есть строка из идущих подряд символов от $$$L$$$-го до $$$R$$$-го включительно), совпадает с префиксом $$$S$$$ такой же длины (то есть с подстрокой, соответствующей подотрезку $$$[1, \ R - L + 1]$$$), то его подозрительность равна минимуму в массиве $$$W$$$ на том же подотрезке $$$[L, \ R]$$$, а иначе она равна $$$0$$$.</p><p>Помогите Феде ответить на все запросы, пока за ним не приехали санитары!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ $$$(1 \leq n \leq 600\,000)$$$ — количество запросов.</p><p>Далее идут $$$n$$$ строк: $$$i$$$-я из них содержит запрос $$$i$$$: строчную букву латинского алфавита $$$c_i$$$ и целое число $$$w_i$$$ $$$(0 \leq w_i \leq 2^{30} - 1)$$$.</p><p>Запросы даны в зашифрованном виде. Пусть $$$ans$$$ — ответ на предыдущий запрос (для первого запроса положим эту величину равной $$$0$$$). Тогда для того, чтобы получить настоящий запрос, с данными числами необходимо проделать следующие операции: $$$c_i$$$ сдвинуть циклически по алфавиту вперёд на $$$ans$$$, а $$$w_i$$$ сделать равным $$$w_i \oplus (ans \ \&amp; \ MASK)$$$, где $$$\oplus$$$ — побитовое исключающее «или», $$$\&amp;$$$ — побитовое «и», а $$$MASK = 2^{30} - 1$$$.</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> 7 a 1 a 0 y 3 y 5 v 4 u 6 r 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 4 5 7 9 12 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 a 2 y 2 z 0 y 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 2 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 a 7 u 5 t 3 s 10 s 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 9 11 12 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для удобства будем называть «подозрительными» те подотрезки, для которых соответствующие им строки являются префиксами $$$S$$$, то есть те, подозрительность которых может быть не нулевой.</p><p>В результате расшифровки в первом примере из условия после всех запросов строка $$$S$$$ равна «abacaba», а все $$$w_i = 1$$$, то есть подозрительность всех подозрительных подотрезков просто равна $$$1$$$. Посмотрим, как получается ответ после каждого запроса:</p><p>1. $$$S$$$ = «a», у массива $$$W$$$ есть единственный подотрезок — $$$[1, \ 1]$$$, и соответствующая ему подстрока равна «a», то есть всей строке $$$S$$$, то есть она является префиксом $$$S$$$, и подозрительность подотрезка равна $$$1$$$.</p><p>2. $$$S$$$ = «ab», подозрительные подотрезки: $$$[1, \ 1]$$$ и $$$[1, \ 2]$$$, всего $$$2$$$.</p><p>3. $$$S$$$ = «aba», подозрительные подотрезки: $$$[1, \ 1]$$$, $$$[1, \ 2]$$$, $$$[1, \ 3]$$$ и $$$[3, \ 3]$$$, всего $$$4$$$.</p><p>4. $$$S$$$ = «abac», подозрительные подотрезки: $$$[1, \ 1]$$$, $$$[1, \ 2]$$$, $$$[1, \ 3]$$$, $$$[1, \ 4]$$$ и $$$[3, \ 3]$$$, всего $$$5$$$.</p><p>5. $$$S$$$ = «abaca», подозрительные подотрезки: $$$[1, \ 1]$$$, $$$[1, \ 2]$$$, $$$[1, \ 3]$$$, $$$[1, \ 4]$$$, $$$[1, \ 5]$$$, $$$[3, \ 3]$$$ и $$$[5, \ 5]$$$, всего $$$7$$$.</p><p>6. $$$S$$$ = «abacab», подозрительные подотрезки: $$$[1, \ 1]$$$, $$$[1, \ 2]$$$, $$$[1, \ 3]$$$, $$$[1, \ 4]$$$, $$$[1, \ 5]$$$, $$$[1, \ 6]$$$, $$$[3, \ 3]$$$, $$$[5, \ 5]$$$ и $$$[5, \ 6]$$$ всего $$$9$$$.</p><p>7. $$$S$$$ = «abacaba», подозрительные подотрезки: $$$[1, \ 1]$$$, $$$[1, \ 2]$$$, $$$[1, \ 3]$$$, $$$[1, \ 4]$$$, $$$[1, \ 5]$$$, $$$[1, \ 6]$$$, $$$[1, \ 7]$$$, $$$[3, \ 3]$$$, $$$[5, \ 5]$$$, $$$[5, \ 6]$$$, $$$[5, \ 7]$$$ и $$$[7, \ 7]$$$ всего $$$12$$$.</p><p>Во втором примере из условия после всех запросов $$$S$$$ = «aaba», $$$W = [2, 0, 2, 0]$$$.</p><p>1. $$$S$$$ = «a», подозрительные подотрезки: $$$[1, \ 1]$$$ (подозрительность $$$2$$$), в сумме $$$2$$$.</p><p>2. $$$S$$$ = «aa», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$2$$$), $$$[1, \ 2]$$$ ($$$0$$$), $$$[2, \ 2]$$$ ($$$0$$$), в сумме $$$2$$$.</p><p>3. $$$S$$$ = «aab», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$2$$$), $$$[1, \ 2]$$$ ($$$0$$$), $$$[1, \ 3]$$$ ($$$0$$$), $$$[2, \ 2]$$$ ($$$0$$$), в сумме $$$2$$$.</p><p>4. $$$S$$$ = «aaba», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$2$$$), $$$[1, \ 2]$$$ ($$$0$$$), $$$[1, \ 3]$$$ ($$$0$$$), $$$[1, \ 4]$$$ ($$$0$$$), $$$[2, \ 2]$$$ ($$$0$$$), $$$[4, \ 4]$$$ ($$$0$$$), в сумме $$$2$$$.</p><p>В третьем примере из условия после всех запросов $$$S$$$ = «abcde», $$$W = [7, 2, 10, 1, 7]$$$.</p><p>1. $$$S$$$ = «a», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$7$$$), в сумме $$$7$$$.</p><p>2. $$$S$$$ = «ab», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$7$$$), $$$[1, \ 2]$$$ ($$$2$$$), в сумме $$$9$$$.</p><p>3. $$$S$$$ = «abc», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$7$$$), $$$[1, \ 2]$$$ ($$$2$$$), $$$[1, \ 3]$$$ ($$$2$$$), в сумме $$$11$$$.</p><p>4. $$$S$$$ = «abcd», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$7$$$), $$$[1, \ 2]$$$ ($$$2$$$), $$$[1, \ 3]$$$ ($$$2$$$), $$$[1, \ 4]$$$ ($$$1$$$), в сумме $$$12$$$.</p><p>5. $$$S$$$ = «abcde», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$7$$$), $$$[1, \ 2]$$$ ($$$2$$$), $$$[1, \ 3]$$$ ($$$2$$$), $$$[1, \ 4]$$$ ($$$1$$$), $$$[1, \ 5]$$$ ($$$1$$$), в сумме $$$13$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="0a84489ca3098f5c3de058d87e4df6e6"/> <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="b76268a612690f667c95bf2c0d8485a22e1d8aa6"/> <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='0a84489ca3098f5c3de058d87e4df6e6'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1286%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='0a84489ca3098f5c3de058d87e4df6e6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1286">Codeforces Round 612 (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='0a84489ca3098f5c3de058d87e4df6e6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1286/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *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='0a84489ca3098f5c3de058d87e4df6e6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509644"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0a84489ca3098f5c3de058d87e4df6e6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509644"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10240:10241" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10252" resourceName="Codeforces Round #612 - 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/1286">Задачи</a></li> <li><a href="/contest/1286/submit">Отослать</a></li> <li><a href="/contest/1286/my">Мои посылки</a></li> <li><a href="/contest/1286/status">Статус</a></li> <li><a href="/contest/1286/hacks">Взломы</a></li> <li><a href="/contest/1286/room/1">Комната</a></li> <li><a href="/contest/1286/standings">Положение</a></li> <li><a href="/contest/1286/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_443451eef4bb4748cff464b20fef085c013c80f8"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Гончар Фёдор наносит ответный удар</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Феди есть строка $$$S$$$, изначально пустая, и массив $$$W$$$, тоже изначально пустой.</p><p>Феде по одному приходят $$$n$$$ запросов к этой строке и этому массиву. Запрос $$$i$$$ состоит из строчной буквы английского алфавита $$$c_i$$$ и целого неотрицательного числа $$$w_i$$$. К строке $$$S$$$ необходимо в конец приписать символ $$$c_i$$$, а к $$$W$$$ в конец добавить $$$w_i$$$. Ответом на запрос является сумма <span class="tex-font-style-it">подозрительностей</span> по всем подотрезкам $$$[L, \ R]$$$ массива $$$W$$$ $$$(1 \leq L \leq R \leq i)$$$.</p><p>Определим <span class="tex-font-style-it">подозрительность</span> подотрезка следующим образом: если подстрока $$$S$$$, соответствующая этому подотрезку (то есть строка из идущих подряд символов от $$$L$$$-го до $$$R$$$-го включительно), совпадает с префиксом $$$S$$$ такой же длины (то есть с подстрокой, соответствующей подотрезку $$$[1, \ R - L + 1]$$$), то его подозрительность равна минимуму в массиве $$$W$$$ на том же подотрезке $$$[L, \ R]$$$, а иначе она равна $$$0$$$.</p><p>Помогите Феде ответить на все запросы, пока за ним не приехали санитары!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ $$$(1 \leq n \leq 600\,000)$$$ — количество запросов.</p><p>Далее идут $$$n$$$ строк: $$$i$$$-я из них содержит запрос $$$i$$$: строчную букву латинского алфавита $$$c_i$$$ и целое число $$$w_i$$$ $$$(0 \leq w_i \leq 2^{30} - 1)$$$.</p><p>Запросы даны в зашифрованном виде. Пусть $$$ans$$$ — ответ на предыдущий запрос (для первого запроса положим эту величину равной $$$0$$$). Тогда для того, чтобы получить настоящий запрос, с данными числами необходимо проделать следующие операции: $$$c_i$$$ сдвинуть циклически по алфавиту вперёд на $$$ans$$$, а $$$w_i$$$ сделать равным $$$w_i \oplus (ans \ \&amp; \ MASK)$$$, где $$$\oplus$$$ — побитовое исключающее «или», $$$\&amp;$$$ — побитовое «и», а $$$MASK = 2^{30} - 1$$$.</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> 7 a 1 a 0 y 3 y 5 v 4 u 6 r 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 4 5 7 9 12 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 a 2 y 2 z 0 y 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 2 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 a 7 u 5 t 3 s 10 s 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 9 11 12 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для удобства будем называть «подозрительными» те подотрезки, для которых соответствующие им строки являются префиксами $$$S$$$, то есть те, подозрительность которых может быть не нулевой.</p><p>В результате расшифровки в первом примере из условия после всех запросов строка $$$S$$$ равна «abacaba», а все $$$w_i = 1$$$, то есть подозрительность всех подозрительных подотрезков просто равна $$$1$$$. Посмотрим, как получается ответ после каждого запроса:</p><p>1. $$$S$$$ = «a», у массива $$$W$$$ есть единственный подотрезок — $$$[1, \ 1]$$$, и соответствующая ему подстрока равна «a», то есть всей строке $$$S$$$, то есть она является префиксом $$$S$$$, и подозрительность подотрезка равна $$$1$$$.</p><p>2. $$$S$$$ = «ab», подозрительные подотрезки: $$$[1, \ 1]$$$ и $$$[1, \ 2]$$$, всего $$$2$$$.</p><p>3. $$$S$$$ = «aba», подозрительные подотрезки: $$$[1, \ 1]$$$, $$$[1, \ 2]$$$, $$$[1, \ 3]$$$ и $$$[3, \ 3]$$$, всего $$$4$$$.</p><p>4. $$$S$$$ = «abac», подозрительные подотрезки: $$$[1, \ 1]$$$, $$$[1, \ 2]$$$, $$$[1, \ 3]$$$, $$$[1, \ 4]$$$ и $$$[3, \ 3]$$$, всего $$$5$$$.</p><p>5. $$$S$$$ = «abaca», подозрительные подотрезки: $$$[1, \ 1]$$$, $$$[1, \ 2]$$$, $$$[1, \ 3]$$$, $$$[1, \ 4]$$$, $$$[1, \ 5]$$$, $$$[3, \ 3]$$$ и $$$[5, \ 5]$$$, всего $$$7$$$.</p><p>6. $$$S$$$ = «abacab», подозрительные подотрезки: $$$[1, \ 1]$$$, $$$[1, \ 2]$$$, $$$[1, \ 3]$$$, $$$[1, \ 4]$$$, $$$[1, \ 5]$$$, $$$[1, \ 6]$$$, $$$[3, \ 3]$$$, $$$[5, \ 5]$$$ и $$$[5, \ 6]$$$ всего $$$9$$$.</p><p>7. $$$S$$$ = «abacaba», подозрительные подотрезки: $$$[1, \ 1]$$$, $$$[1, \ 2]$$$, $$$[1, \ 3]$$$, $$$[1, \ 4]$$$, $$$[1, \ 5]$$$, $$$[1, \ 6]$$$, $$$[1, \ 7]$$$, $$$[3, \ 3]$$$, $$$[5, \ 5]$$$, $$$[5, \ 6]$$$, $$$[5, \ 7]$$$ и $$$[7, \ 7]$$$ всего $$$12$$$.</p><p>Во втором примере из условия после всех запросов $$$S$$$ = «aaba», $$$W = [2, 0, 2, 0]$$$.</p><p>1. $$$S$$$ = «a», подозрительные подотрезки: $$$[1, \ 1]$$$ (подозрительность $$$2$$$), в сумме $$$2$$$.</p><p>2. $$$S$$$ = «aa», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$2$$$), $$$[1, \ 2]$$$ ($$$0$$$), $$$[2, \ 2]$$$ ($$$0$$$), в сумме $$$2$$$.</p><p>3. $$$S$$$ = «aab», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$2$$$), $$$[1, \ 2]$$$ ($$$0$$$), $$$[1, \ 3]$$$ ($$$0$$$), $$$[2, \ 2]$$$ ($$$0$$$), в сумме $$$2$$$.</p><p>4. $$$S$$$ = «aaba», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$2$$$), $$$[1, \ 2]$$$ ($$$0$$$), $$$[1, \ 3]$$$ ($$$0$$$), $$$[1, \ 4]$$$ ($$$0$$$), $$$[2, \ 2]$$$ ($$$0$$$), $$$[4, \ 4]$$$ ($$$0$$$), в сумме $$$2$$$.</p><p>В третьем примере из условия после всех запросов $$$S$$$ = «abcde», $$$W = [7, 2, 10, 1, 7]$$$.</p><p>1. $$$S$$$ = «a», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$7$$$), в сумме $$$7$$$.</p><p>2. $$$S$$$ = «ab», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$7$$$), $$$[1, \ 2]$$$ ($$$2$$$), в сумме $$$9$$$.</p><p>3. $$$S$$$ = «abc», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$7$$$), $$$[1, \ 2]$$$ ($$$2$$$), $$$[1, \ 3]$$$ ($$$2$$$), в сумме $$$11$$$.</p><p>4. $$$S$$$ = «abcd», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$7$$$), $$$[1, \ 2]$$$ ($$$2$$$), $$$[1, \ 3]$$$ ($$$2$$$), $$$[1, \ 4]$$$ ($$$1$$$), в сумме $$$12$$$.</p><p>5. $$$S$$$ = «abcde», подозрительные подотрезки: $$$[1, \ 1]$$$ ($$$7$$$), $$$[1, \ 2]$$$ ($$$2$$$), $$$[1, \ 3]$$$ ($$$2$$$), $$$[1, \ 4]$$$ ($$$1$$$), $$$[1, \ 5]$$$ ($$$1$$$), в сумме $$$13$$$.</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:54:31</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'8124939a0e90161c',t:'MTY5NjY2NTI3MS41MDQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\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\u043e\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3200"]
1286F
1286
F
ru
F. Гарри Гончар
<div class="problem-statement"><div class="header"><div class="title">F. Гарри Гончар</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>9 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Как известно, чтобы победить лорда Волан-де-Морта, Гарри необходимо сперва уничтожить все крестражи. Последний крестраж лорда Сами-Знаете-кого представляет собой массив $$$a$$$ состоящий из $$$n$$$ целых чисел, который Гарри необходимо уничтожить. Массив считается уничтоженным, если все его элементы равны 0. Чтобы его уничтожить, Гарри может производить два типа операций:</p><ol> <li> выбрать индекс $$$i$$$ ($$$1 \le i \le n$$$), целое число $$$x$$$ и вычесть из $$$a_i$$$ число $$$x$$$.</li><li> выбрать индексы $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n; i \ne j$$$), целое число $$$x$$$ и вычесть из $$$a_i$$$ число $$$x$$$, а из $$$a_j$$$ — число $$$x + 1$$$. </li></ol><p>Обратите внимание, что $$$x$$$ может быть произвольным, в том числе и отрицательным.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/8a4946e00a5c854b3a230fb6ea472db9e68dca36.png" style="max-width: 100.0%;max-height: 100.0%;"/></center><p>У Гарри осталось совсем немного времени. Помогите ему и узнайте, какое минимальное число операций с массивом ему придётся совершить, чтобы уничтожить массив и покончить с лордом Волан-де-Мортом!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ — количество элементов в массиве $$$a$$$ ($$$1 \le n \le 20$$$). </p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ — элементы массива ($$$-10^{15} \le a_i \le 10^{15}$$$).</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 1 10 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 3 -2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно три раза применить операцию первого типа к массиву.</p><p>Во втором примере можно два раза применить операцию второго типа: сначала выбрать $$$i = 2, j = 1, x = 4$$$ и получить массив $$$(0, -1, -2)$$$, затем выбрать $$$i = 3, j = 2, x = -2$$$ чтобы уничтожить массив.</p><p>В третьем примере ничего делать не надо, так как массив уже состоит из нулей.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="6460b97143e9ce4c5220285249910236"/> <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="b76268a612690f667c95bf2c0d8485a22e1d8aa6"/> <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='6460b97143e9ce4c5220285249910236'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1286%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='6460b97143e9ce4c5220285249910236'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1286">Codeforces Round 612 (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='6460b97143e9ce4c5220285249910236'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1286/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Быстрое преобразование Фурье"> бпф </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='6460b97143e9ce4c5220285249910236'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509645"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6460b97143e9ce4c5220285249910236'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509645"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10240:10241" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10252" resourceName="Codeforces Round #612 - 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/1286">Задачи</a></li> <li><a href="/contest/1286/submit">Отослать</a></li> <li><a href="/contest/1286/my">Мои посылки</a></li> <li><a href="/contest/1286/status">Статус</a></li> <li><a href="/contest/1286/hacks">Взломы</a></li> <li><a href="/contest/1286/room/1">Комната</a></li> <li><a href="/contest/1286/standings">Положение</a></li> <li><a href="/contest/1286/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_64f4d7d1e3c6ef3e3df1856fc3f8c5a26bb88372"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>9 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Как известно, чтобы победить лорда Волан-де-Морта, Гарри необходимо сперва уничтожить все крестражи. Последний крестраж лорда Сами-Знаете-кого представляет собой массив $$$a$$$ состоящий из $$$n$$$ целых чисел, который Гарри необходимо уничтожить. Массив считается уничтоженным, если все его элементы равны 0. Чтобы его уничтожить, Гарри может производить два типа операций:</p><ol> <li> выбрать индекс $$$i$$$ ($$$1 \le i \le n$$$), целое число $$$x$$$ и вычесть из $$$a_i$$$ число $$$x$$$.</li><li> выбрать индексы $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n; i \ne j$$$), целое число $$$x$$$ и вычесть из $$$a_i$$$ число $$$x$$$, а из $$$a_j$$$ — число $$$x + 1$$$. </li></ol><p>Обратите внимание, что $$$x$$$ может быть произвольным, в том числе и отрицательным.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/8a4946e00a5c854b3a230fb6ea472db9e68dca36.png" style="max-width: 100.0%;max-height: 100.0%;" /></center><p>У Гарри осталось совсем немного времени. Помогите ему и узнайте, какое минимальное число операций с массивом ему придётся совершить, чтобы уничтожить массив и покончить с лордом Волан-де-Мортом!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ — количество элементов в массиве $$$a$$$ ($$$1 \le n \le 20$$$). </p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ — элементы массива ($$$-10^{15} \le a_i \le 10^{15}$$$).</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 1 10 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 3 -2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно три раза применить операцию первого типа к массиву.</p><p>Во втором примере можно два раза применить операцию второго типа: сначала выбрать $$$i = 2, j = 1, x = 4$$$ и получить массив $$$(0, -1, -2)$$$, затем выбрать $$$i = 3, j = 2, x = -2$$$ чтобы уничтожить массив.</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:54:34</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'812493a28cbf9d46',t:'MTY5NjY2NTI3NS4wMDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u044b\u0441\u0442\u0440\u043e\u0435 \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u0424\u0443\u0440\u044c\u0435", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u043f\u0444", "\u0434\u043f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*3100"]
1287A
1287
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>В ЛКШ.Зима день экскурсий, поэтому $$$t$$$ групп школьников отправились в Торжок. Тротуары в Торжке настолько узкие, что идти приходится в колонне по-одному.</p><p>Изначально некоторые из школьников злы. Для удобства будем описывать группу школьников строкой из заглавных латинских букв «<span class="tex-font-style-tt">A</span>» и «<span class="tex-font-style-tt">P</span>»: </p><ul> <li> «<span class="tex-font-style-tt">A</span>» соответствует злому школьнику </li><li> «<span class="tex-font-style-tt">P</span>» соответствует спокойному школьнику </li></ul><p>Строка описывает школьников от последнего к первому, слева направо.</p><p>Каждую минуту каждый злой школьник кидает снежок в спину идущего непосредственно перед ним. </p><p>Формально, если злой школьник соответствует символу заданной строки с индексом $$$i$$$, то снежок он будет кидать в школьника, который соответствует символу с индексом $$$i+1$$$ (студенты в строке заданы от последнего к первому!). Если школьник, в которого попали снежком, еще не был зол, то он становится злым. Даже если первый (самый правый в строке) школьник является злым, он не бросает снежок, так как впереди него нет другого ученика.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/1f23da2c35f2376e3a2106b44196e6e8b0b2a999.png" style="max-width: 100.0%;max-height: 100.0%;"/></center><p>Рассмотрим первый тестовый пример. В нем колонна изначально имеет такой вид: <span class="tex-font-style-tt">PPAP</span>. Через минуту единственный злой школьник кинет снежок в школьника, идущего перед ним, и он тоже станет злым: <span class="tex-font-style-tt">PPAA</span>. После этого, новых злых школьников появляться не будет.</p><p>Помогите преподавателям ЛКШ.Зима определить для каждой группы время, спустя которое в ней появится последний злой школьник.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано число $$$t$$$ ($$$1 \le t \le 100$$$) — количество групп школьников. Следующие $$$2t$$$ строк описывают группы школьников.</p><p>Описание группы начинается с целого числа $$$k_i$$$ ($$$1 \le k_i \le 100$$$) — количество школьников в группе, затем дана строка $$$s_i$$$, состоящая из $$$k_i$$$ символов «<span class="tex-font-style-tt">A</span>» и «<span class="tex-font-style-tt">P</span>», описывающая $$$i$$$-ю группу школьников.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждой группы выведите в отдельной строке одно целое число — количество минут, через которое в этой группе появится последний злой школьник.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 4 PPAP </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 12 APPAPPPAPPPP 3 AAP 3 PPA </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере через $$$1$$$ минуту состояния школьников станут такими: <span class="tex-font-style-tt">PPAA</span> после этого новых злых школьников не появится.</p><p>Во втором примере состояния школьников в первой группе по минутам будут выглядеть так: </p><ul> <li> через $$$1$$$ минуту — <span class="tex-font-style-tt">AAPAAPPAAPPP</span> </li><li> через $$$2$$$ минуты — <span class="tex-font-style-tt">AAAAAAPAAAPP</span> </li><li> через $$$3$$$ минуты — <span class="tex-font-style-tt">AAAAAAAAAAAP</span> </li><li> через $$$4$$$ минуты злыми станут все $$$12$$$ школьников, поэтому новых злых школьников не появится. </li></ul><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="50e73edf6b6d9988dedd90ca6f6c6182"/> <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="a3f727fbd8fb1cd5fd13bd2927088ade7af51ba9"/> <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='50e73edf6b6d9988dedd90ca6f6c6182'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1287%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='50e73edf6b6d9988dedd90ca6f6c6182'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1287">Codeforces Round 612 (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='50e73edf6b6d9988dedd90ca6f6c6182'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1287/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='50e73edf6b6d9988dedd90ca6f6c6182'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509646"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='50e73edf6b6d9988dedd90ca6f6c6182'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509646"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10242:10243" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10251" resourceName="Codeforces Round #612 - 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/1287">Задачи</a></li> <li><a href="/contest/1287/submit">Отослать</a></li> <li><a href="/contest/1287/my">Мои посылки</a></li> <li><a href="/contest/1287/status">Статус</a></li> <li><a href="/contest/1287/hacks">Взломы</a></li> <li><a href="/contest/1287/room/1">Комната</a></li> <li><a href="/contest/1287/standings">Положение</a></li> <li><a href="/contest/1287/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f22f7a8545cd01fd95643921a0607a53415ef3e1"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>В ЛКШ.Зима день экскурсий, поэтому $$$t$$$ групп школьников отправились в Торжок. Тротуары в Торжке настолько узкие, что идти приходится в колонне по-одному.</p><p>Изначально некоторые из школьников злы. Для удобства будем описывать группу школьников строкой из заглавных латинских букв «<span class="tex-font-style-tt">A</span>» и «<span class="tex-font-style-tt">P</span>»: </p><ul> <li> «<span class="tex-font-style-tt">A</span>» соответствует злому школьнику </li><li> «<span class="tex-font-style-tt">P</span>» соответствует спокойному школьнику </li></ul><p>Строка описывает школьников от последнего к первому, слева направо.</p><p>Каждую минуту каждый злой школьник кидает снежок в спину идущего непосредственно перед ним. </p><p>Формально, если злой школьник соответствует символу заданной строки с индексом $$$i$$$, то снежок он будет кидать в школьника, который соответствует символу с индексом $$$i+1$$$ (студенты в строке заданы от последнего к первому!). Если школьник, в которого попали снежком, еще не был зол, то он становится злым. Даже если первый (самый правый в строке) школьник является злым, он не бросает снежок, так как впереди него нет другого ученика.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/1f23da2c35f2376e3a2106b44196e6e8b0b2a999.png" style="max-width: 100.0%;max-height: 100.0%;" /></center><p>Рассмотрим первый тестовый пример. В нем колонна изначально имеет такой вид: <span class="tex-font-style-tt">PPAP</span>. Через минуту единственный злой школьник кинет снежок в школьника, идущего перед ним, и он тоже станет злым: <span class="tex-font-style-tt">PPAA</span>. После этого, новых злых школьников появляться не будет.</p><p>Помогите преподавателям ЛКШ.Зима определить для каждой группы время, спустя которое в ней появится последний злой школьник.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано число $$$t$$$ ($$$1 \le t \le 100$$$) — количество групп школьников. Следующие $$$2t$$$ строк описывают группы школьников.</p><p>Описание группы начинается с целого числа $$$k_i$$$ ($$$1 \le k_i \le 100$$$) — количество школьников в группе, затем дана строка $$$s_i$$$, состоящая из $$$k_i$$$ символов «<span class="tex-font-style-tt">A</span>» и «<span class="tex-font-style-tt">P</span>», описывающая $$$i$$$-ю группу школьников.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждой группы выведите в отдельной строке одно целое число — количество минут, через которое в этой группе появится последний злой школьник.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 4 PPAP </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 12 APPAPPPAPPPP 3 AAP 3 PPA </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере через $$$1$$$ минуту состояния школьников станут такими: <span class="tex-font-style-tt">PPAA</span> после этого новых злых школьников не появится.</p><p>Во втором примере состояния школьников в первой группе по минутам будут выглядеть так: </p><ul> <li> через $$$1$$$ минуту — <span class="tex-font-style-tt">AAPAAPPAAPPP</span> </li><li> через $$$2$$$ минуты — <span class="tex-font-style-tt">AAAAAAPAAAPP</span> </li><li> через $$$3$$$ минуты — <span class="tex-font-style-tt">AAAAAAAAAAAP</span> </li><li> через $$$4$$$ минуты злыми станут все $$$12$$$ школьников, поэтому новых злых школьников не появится. </li></ul><p>Во второй группе второго примера через $$$1$$$ минуту все школьники станут злыми.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:54: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:'812493b88c5e9dae',t:'MTY5NjY2NTI3Ni40NzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*800"]
1287B
1287
B
ru
B. Гиперсет
<div class="problem-statement"><div class="header"><div class="title">B. Гиперсет</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Пчёлки Алиса и Алеся подарили пчеловодке Полине на Новый Год знаменитую карточную игру «Set». Колода для игры состоит из карт, каждая из которых обладает набором из четырех признаков: тип фигуры, количество фигур, их цвет и текстура. <span class="tex-font-style-it">Сетом</span> называется тройка карт, у которых каждый признак либо у всех попарно отличается, либо совпадает. Рисунок ниже иллюстрирует возможные комбинации карт.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/70881206ecd405e255ef0888da06e409ca3692ca.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Полина придумала новый вариант игры и назвала его «Hyperset». В этой игре есть $$$n$$$ карт, обладающих $$$k$$$ признаками, каждый из которых принимает значение «<span class="tex-font-style-tt">S</span>», «<span class="tex-font-style-tt">E</span>» или «<span class="tex-font-style-tt">T</span>». Оригинальная игра «Set» может быть рассмотрена как «Hyperset» с $$$k = 4$$$.</p><p>Так же, как и раньше, в этой игре <span class="tex-font-style-it">сетом</span> все еще называется тройка карт, у которых каждый признак либо попарно отличается, либо совпадает. Цель игры очень проста: нужно найти количество способов выбрать три карты, образующие сет.</p><p>К сожалению, зимние каникулы подошли к концу, и Полине уже надо идти в школу. Помогите Полине найти количество сетов среди карт, лежащих на столе.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 1500$$$, $$$1 \le k \le 30$$$) — количество карт и количество признаков соответственно.</p><p>В каждой из следующих $$$n$$$ строк содержится описание карт. Описание карты представляет собой строку, состоящую из $$$k$$$ букв «<span class="tex-font-style-tt">S</span>», «<span class="tex-font-style-tt">E</span>», «<span class="tex-font-style-tt">T</span>». Символ на позиции $$$i$$$ описывает $$$i$$$-й признак этой карты. Все карты различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — количество способов выбрать три карты, образующих сет.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 SET ETS TSE </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 SETE ETSE TSES </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 4 SETT TEST EEET ESTE STES </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В третьем примере сетами являются следующие тройки карт:</p><ol> <li> «<span class="tex-font-style-tt">SETT</span>», «<span class="tex-font-style-tt">TEST</span>», «<span class="tex-font-style-tt">EEET</span>» </li><li> «<span class="tex-font-style-tt">TEST</span>», «<span class="tex-font-style-tt">ESTE</span>», «<span class="tex-font-style-tt">STES</span>» </li></ol></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="62611028a91569663f8dd5d8b891aa40"/> <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="a3f727fbd8fb1cd5fd13bd2927088ade7af51ba9"/> <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='62611028a91569663f8dd5d8b891aa40'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1287%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='62611028a91569663f8dd5d8b891aa40'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1287">Codeforces Round 612 (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='62611028a91569663f8dd5d8b891aa40'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1287/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='62611028a91569663f8dd5d8b891aa40'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509647"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='62611028a91569663f8dd5d8b891aa40'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509647"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10242:10243" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10251" resourceName="Codeforces Round #612 - 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/1287">Задачи</a></li> <li><a href="/contest/1287/submit">Отослать</a></li> <li><a href="/contest/1287/my">Мои посылки</a></li> <li><a href="/contest/1287/status">Статус</a></li> <li><a href="/contest/1287/hacks">Взломы</a></li> <li><a href="/contest/1287/room/1">Комната</a></li> <li><a href="/contest/1287/standings">Положение</a></li> <li><a href="/contest/1287/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0198773ab768006270e543535609fab525436444"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Гиперсет</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Пчёлки Алиса и Алеся подарили пчеловодке Полине на Новый Год знаменитую карточную игру «Set». Колода для игры состоит из карт, каждая из которых обладает набором из четырех признаков: тип фигуры, количество фигур, их цвет и текстура. <span class="tex-font-style-it">Сетом</span> называется тройка карт, у которых каждый признак либо у всех попарно отличается, либо совпадает. Рисунок ниже иллюстрирует возможные комбинации карт.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/70881206ecd405e255ef0888da06e409ca3692ca.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Полина придумала новый вариант игры и назвала его «Hyperset». В этой игре есть $$$n$$$ карт, обладающих $$$k$$$ признаками, каждый из которых принимает значение «<span class="tex-font-style-tt">S</span>», «<span class="tex-font-style-tt">E</span>» или «<span class="tex-font-style-tt">T</span>». Оригинальная игра «Set» может быть рассмотрена как «Hyperset» с $$$k = 4$$$.</p><p>Так же, как и раньше, в этой игре <span class="tex-font-style-it">сетом</span> все еще называется тройка карт, у которых каждый признак либо попарно отличается, либо совпадает. Цель игры очень проста: нужно найти количество способов выбрать три карты, образующие сет.</p><p>К сожалению, зимние каникулы подошли к концу, и Полине уже надо идти в школу. Помогите Полине найти количество сетов среди карт, лежащих на столе.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 1500$$$, $$$1 \le k \le 30$$$) — количество карт и количество признаков соответственно.</p><p>В каждой из следующих $$$n$$$ строк содержится описание карт. Описание карты представляет собой строку, состоящую из $$$k$$$ букв «<span class="tex-font-style-tt">S</span>», «<span class="tex-font-style-tt">E</span>», «<span class="tex-font-style-tt">T</span>». Символ на позиции $$$i$$$ описывает $$$i$$$-й признак этой карты. Все карты различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — количество способов выбрать три карты, образующих сет.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 SET ETS TSE </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 SETE ETSE TSES </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 4 SETT TEST EEET ESTE STES </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В третьем примере сетами являются следующие тройки карт:</p><ol> <li> «<span class="tex-font-style-tt">SETT</span>», «<span class="tex-font-style-tt">TEST</span>», «<span class="tex-font-style-tt">EEET</span>» </li><li> «<span class="tex-font-style-tt">TEST</span>», «<span class="tex-font-style-tt">ESTE</span>», «<span class="tex-font-style-tt">STES</span>» </li></ol></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'812493c1bb1a9d9e',t:'MTY5NjY2NTI3Ny45MTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1500"]
1287C
1287
C
ru
C. Гирлянда
<div class="problem-statement"><div class="header"><div class="title">C. Гирлянда</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вадим очень любит наряжать новогоднюю ёлку, поэтому ему подарили невероятно красивую гирлянду. Она состоит из $$$n$$$ лампочек, расположенных в ряд. На каждой лампочке написано число от $$$1$$$ до $$$n$$$, причем все числа различны и шли в произвольном порядке. Пока Вадим решал задачи, его домашний Карась снял с гирлянды некоторые лампочки. Теперь Вадим хочет вернуть их на место.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/c87ff8b17badad0f05d83d783c8343a0a00725a6.png" style="max-width: 100.0%;max-height: 100.0%;"/></center><p>Вадим хочет повесить все лампочки обратно на гирлянду. Он считает <span class="tex-font-style-it">сложностью</span> гирлянды количество пар соседних лампочек, на которых написаны числа разной четности (то есть имеющие разные остатки при делении на $$$2$$$). Например, сложность гирлянды <span class="tex-font-style-tt">1 4 2 3 5</span> равна $$$2$$$, а сложность гирлянды <span class="tex-font-style-tt">1 3 5 7 6 4 2</span>, равна $$$1$$$.</p><p>Никто не любит сложности, поэтому Вадим хочет минимизировать количество таких пар. Найдите способ повесить снятые лампочки на гирлянду, чтобы минимизировать ее сложность.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — количество лампочек в гирлянде.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$p_1,\ p_2,\ \ldots,\ p_n$$$ ($$$0 \le p_i \le n$$$) — номер $$$i$$$-й лампочки или $$$0$$$, если Карась ее снял.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — минимальную <span class="tex-font-style-it">сложность</span> гирлянды. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 0 5 0 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 1 0 0 5 0 0 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>В первом примере надо расставить лампочки как <span class="tex-font-style-tt">1 5 4 2 3</span>. В этом случае сложность будет равна 2, так как рядом расположены пары лампочек $$$(5, 4)$$$ и $$$(2, 3)$$$.</p><p>Во втором примере один из правильных ответов <span class="tex-font-style-tt">1 7 3 5 6 4 2</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="b859d0a654e3cc9c5d2d616cf93cec7c"/> <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="a3f727fbd8fb1cd5fd13bd2927088ade7af51ba9"/> <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='b859d0a654e3cc9c5d2d616cf93cec7c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1287%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='b859d0a654e3cc9c5d2d616cf93cec7c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1287">Codeforces Round 612 (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='b859d0a654e3cc9c5d2d616cf93cec7c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1287/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='b859d0a654e3cc9c5d2d616cf93cec7c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509648"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b859d0a654e3cc9c5d2d616cf93cec7c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509648"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10242:10243" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10251" resourceName="Codeforces Round #612 - 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/1287">Задачи</a></li> <li><a href="/contest/1287/submit">Отослать</a></li> <li><a href="/contest/1287/my">Мои посылки</a></li> <li><a href="/contest/1287/status">Статус</a></li> <li><a href="/contest/1287/hacks">Взломы</a></li> <li><a href="/contest/1287/room/1">Комната</a></li> <li><a href="/contest/1287/standings">Положение</a></li> <li><a href="/contest/1287/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_486c81756ffbb6e0d13fdf1b74dc72db201addb0"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Гирлянда</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вадим очень любит наряжать новогоднюю ёлку, поэтому ему подарили невероятно красивую гирлянду. Она состоит из $$$n$$$ лампочек, расположенных в ряд. На каждой лампочке написано число от $$$1$$$ до $$$n$$$, причем все числа различны и шли в произвольном порядке. Пока Вадим решал задачи, его домашний Карась снял с гирлянды некоторые лампочки. Теперь Вадим хочет вернуть их на место.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/c87ff8b17badad0f05d83d783c8343a0a00725a6.png" style="max-width: 100.0%;max-height: 100.0%;" /></center><p>Вадим хочет повесить все лампочки обратно на гирлянду. Он считает <span class="tex-font-style-it">сложностью</span> гирлянды количество пар соседних лампочек, на которых написаны числа разной четности (то есть имеющие разные остатки при делении на $$$2$$$). Например, сложность гирлянды <span class="tex-font-style-tt">1 4 2 3 5</span> равна $$$2$$$, а сложность гирлянды <span class="tex-font-style-tt">1 3 5 7 6 4 2</span>, равна $$$1$$$.</p><p>Никто не любит сложности, поэтому Вадим хочет минимизировать количество таких пар. Найдите способ повесить снятые лампочки на гирлянду, чтобы минимизировать ее сложность.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — количество лампочек в гирлянде.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$p_1,\ p_2,\ \ldots,\ p_n$$$ ($$$0 \le p_i \le n$$$) — номер $$$i$$$-й лампочки или $$$0$$$, если Карась ее снял.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — минимальную <span class="tex-font-style-it">сложность</span> гирлянды. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 0 5 0 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 1 0 0 5 0 0 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>В первом примере надо расставить лампочки как <span class="tex-font-style-tt">1 5 4 2 3</span>. В этом случае сложность будет равна 2, так как рядом расположены пары лампочек $$$(5, 4)$$$ и $$$(2, 3)$$$.</p><p>Во втором примере один из правильных ответов <span class="tex-font-style-tt">1 7 3 5 6 4 2</span>. </p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'812493caacde4d8c',t:'MTY5NjY2NTI3OS4yMjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1800"]
1287D
1287
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>Евлампию подарили корневое дерево, вершины которого пронумерованы от $$$1$$$ до $$$n$$$. В каждой $$$i$$$-й вершине написано число $$$a_i$$$. Евлампий посчитал для каждой вершины $$$i$$$ величину $$$c_i$$$ — количество вершин $$$j$$$ в поддереве вершины $$$i$$$, для которых $$$a_j &lt; a_i$$$.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/0578b7af7f1f0aec057b6485b22c80a6adb3e4c8.png" style="max-width: 100.0%;max-height: 100.0%;"/>Иллюстрация ко второму примеру, первым написано $$$a_i$$$, а в скобках написано $$$c_i$$$</center><p>После нового года Евлампий не смог вспомнить, каким был его подарок! Он помнит дерево и значения $$$c_i$$$, однако совсем забыл, какие числа $$$a_i$$$ были написаны в вершинах. Помогите ему восстановить исходные числа!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится целое число $$$n$$$ $$$(1 \leq n \leq 2000)$$$ — количество вершин в дереве.</p><p>Далее в $$$n$$$ строках идёт описание вершин дерева: в $$$i$$$-й строке находятся два целых числа $$$p_i$$$ и $$$c_i$$$ ($$$0 \leq p_i \leq n$$$; $$$0 \leq c_i \leq n-1$$$), где $$$p_i$$$ — номер родителя вершины $$$i$$$ или $$$0$$$ для корня дерева, а $$$c_i$$$ — количество вершин $$$j$$$ в поддереве вершины $$$i$$$, для которых $$$a_j &lt; a_i$$$.</p><p>Гарантируется, что значения $$$p_i$$$ задают некоторое корневое дерево из $$$n$$$ вершин.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если решение существует, то в первой строке выведите «<span class="tex-font-style-tt">YES</span>», а во второй строке выведите $$$n$$$ чисел $$$a_i$$$ $$$(1 \leq a_i \leq {10}^{9})$$$ — искомые числа, которые были записаны в вершинах дерева. Если решений несколько, выведите любое из них. Можно показать, что если решение существует, то также существует решение, где все $$$a_i$$$ лежат от $$$1$$$ до $$$10^9$$$.</p><p>Если же решения не существует, то выведите «<span class="tex-font-style-tt">NO</span>».</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 0 0 2 2 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 1 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 1 1 3 2 1 3 0 2 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 2 3 2 1 2 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="73dddfb1a02565ab26f72c981caadc53"/> <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="a3f727fbd8fb1cd5fd13bd2927088ade7af51ba9"/> <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='73dddfb1a02565ab26f72c981caadc53'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1287%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='73dddfb1a02565ab26f72c981caadc53'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1287">Codeforces Round 612 (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='73dddfb1a02565ab26f72c981caadc53'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1287/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='73dddfb1a02565ab26f72c981caadc53'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509649"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='73dddfb1a02565ab26f72c981caadc53'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509649"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10242:10243" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10251" resourceName="Codeforces Round #612 - 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/1287">Задачи</a></li> <li><a href="/contest/1287/submit">Отослать</a></li> <li><a href="/contest/1287/my">Мои посылки</a></li> <li><a href="/contest/1287/status">Статус</a></li> <li><a href="/contest/1287/hacks">Взломы</a></li> <li><a href="/contest/1287/room/1">Комната</a></li> <li><a href="/contest/1287/standings">Положение</a></li> <li><a href="/contest/1287/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b6ab58d4a6801329dacb25c9bbb5ce7b61d5ef48"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Евлампию подарили корневое дерево, вершины которого пронумерованы от $$$1$$$ до $$$n$$$. В каждой $$$i$$$-й вершине написано число $$$a_i$$$. Евлампий посчитал для каждой вершины $$$i$$$ величину $$$c_i$$$ — количество вершин $$$j$$$ в поддереве вершины $$$i$$$, для которых $$$a_j &lt; a_i$$$.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/0578b7af7f1f0aec057b6485b22c80a6adb3e4c8.png" style="max-width: 100.0%;max-height: 100.0%;" />Иллюстрация ко второму примеру, первым написано $$$a_i$$$, а в скобках написано $$$c_i$$$</center><p>После нового года Евлампий не смог вспомнить, каким был его подарок! Он помнит дерево и значения $$$c_i$$$, однако совсем забыл, какие числа $$$a_i$$$ были написаны в вершинах. Помогите ему восстановить исходные числа!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится целое число $$$n$$$ $$$(1 \leq n \leq 2000)$$$ — количество вершин в дереве.</p><p>Далее в $$$n$$$ строках идёт описание вершин дерева: в $$$i$$$-й строке находятся два целых числа $$$p_i$$$ и $$$c_i$$$ ($$$0 \leq p_i \leq n$$$; $$$0 \leq c_i \leq n-1$$$), где $$$p_i$$$ — номер родителя вершины $$$i$$$ или $$$0$$$ для корня дерева, а $$$c_i$$$ — количество вершин $$$j$$$ в поддереве вершины $$$i$$$, для которых $$$a_j &lt; a_i$$$.</p><p>Гарантируется, что значения $$$p_i$$$ задают некоторое корневое дерево из $$$n$$$ вершин.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если решение существует, то в первой строке выведите «<span class="tex-font-style-tt">YES</span>», а во второй строке выведите $$$n$$$ чисел $$$a_i$$$ $$$(1 \leq a_i \leq {10}^{9})$$$ — искомые числа, которые были записаны в вершинах дерева. Если решений несколько, выведите любое из них. Можно показать, что если решение существует, то также существует решение, где все $$$a_i$$$ лежат от $$$1$$$ до $$$10^9$$$.</p><p>Если же решения не существует, то выведите «<span class="tex-font-style-tt">NO</span>».</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 0 0 2 2 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 1 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 1 1 3 2 1 3 0 2 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 2 3 2 1 2 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'812493d2ec749d87',t:'MTY5NjY2NTI4MC41MjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1800"]
1287E1
1287
E1
ru
E1. Дурдом (простая версия)
<div class="problem-statement"><div class="header"><div class="title">E1. Дурдом (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Эта задача отличается от сложной версии только ограничением на суммарную длину ответов</span></p><p><span class="tex-font-style-bf">Это интерактивная задача</span>.</p><p>Веня приехал на экскурсию в дурдом, в котором санитары играют с пациентами в следующую игру: санитары загадывают строку $$$s$$$ длины $$$n$$$, состоящую только из строчных букв английского алфавита. Пациент может делать запросы двух типов: </p><ul> <li> <span class="tex-font-style-tt">? l r</span> — запросить все подстроки $$$s[l..r]$$$. При этом в ответе все подстроки будут перемешаны, а в каждой из подстрок будут перемешаны буквы. </li><li> <span class="tex-font-style-tt">! s</span> — сделать предположение о загаданной строке. Этот запрос нужно сделать ровно один раз, после него игра завершается. Если строка угадана, то пациент побеждает, а иначе проигрывает. </li></ul><p>Пациенту разрешено сделать <span class="tex-font-style-bf">не более $$$3$$$ запросов</span> первого типа. Чтобы игра была не так утомительна для санитаров, существует следующее ограничение: суммарно на запросы первого типа должно быть возвращено не более $$$(n+1)^2$$$ подстрок.</p><p>Помогите пациенту выиграть и выбраться из дурдома!</p><p>После запроса второго типа ваша программа должна немедленно завершиться. В случае, если ваша программа неверно угадает строку или превысит заданные ограничения на количество запросов или количество возвращенных подстрок, она получит вердикт <span class="tex-font-style-tt">Неправильный ответ</span>.</p><p>Обратите внимание, что в каждом тесте строка фиксирована и не меняется в ходе игры. Иными словами, интерактор не адаптивен.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая и единственная строка содержит число $$$n$$$ ($$$1 \le n \le 100$$$) — длину загадываемой строки.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Вы начинаете своё взаимодействие, считав $$$n$$$.</p><p>Для того, чтобы задать вопрос о подстроке с $$$l$$$ по $$$r$$$ включительно ($$$1 \le l \le r \le n$$$) выведите в отдельной строке</p><p><span class="tex-font-style-tt">? l r</span></p><p>В ответ вы получите все подстроки строки $$$s[l..r]$$$ в случайном порядке, каждую ровно один раз. В каждой из подстрок будут случайным образом перемешаны буквы. </p><p>В случае, если вы сделаете некорректный запрос, зададите более $$$3$$$ запросов данного типа, или в результате заданных запросов Вам будет возвращено суммарно более $$$(n+1)^2$$$ подстрок, то ваше решение получит вердикт <span class="tex-font-style-bf">Неправильный ответ</span>.</p><p>Для того, чтобы сделать предположение о загаданной строке $$$s$$$ выведите в отдельной строке</p><p><span class="tex-font-style-tt">! s</span></p><p>После вывода каждого запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> fflush(stdout) или cout.flush() в C++; </li><li> System.out.flush() в Java; </li><li> flush(output) в Pascal; </li><li> stdout.flush() в Python; </li><li> смотрите документацию для других языков. </li></ul><p>Если вы получили строку <span class="tex-font-style-tt">-</span> (дефис) в качестве ответа на какой-либо запрос, то вам надо завершить программу штатным образом с кодом возврата 0 (например, сделав <span class="tex-font-style-tt">exit(0)</span>). Это означает, что интерактор зафиксировал ошибку в протоколе или поведении программы. Если вы не завершите в этом случае программу штатным образом с кодом возврата 0, то можете получить любой неуспешный вердикт.</p><p><span class="tex-font-style-bf">Формат взломов</span></p><p>Для взломов используйте следующий формат:</p><p>В первой строке должно быть единственное число $$$n$$$ ($$$1 \le n \le 100$$$) — длина загадываемой строки.</p><p>Во второй строке выведите строку $$$s$$$ — сама загадываемая строка.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 a aa a cb b c c</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 2 ? 3 4 ? 4 4 ! aabc</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="79ec99efb16907d219ddc428305d738e"/> <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="a3f727fbd8fb1cd5fd13bd2927088ade7af51ba9"/> <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='79ec99efb16907d219ddc428305d738e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1287%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='79ec99efb16907d219ddc428305d738e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1287">Codeforces Round 612 (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='79ec99efb16907d219ddc428305d738e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1287/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='79ec99efb16907d219ddc428305d738e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509650"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='79ec99efb16907d219ddc428305d738e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509650"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10242:10243" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10251" resourceName="Codeforces Round #612 - 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/1287">Задачи</a></li> <li><a href="/contest/1287/submit">Отослать</a></li> <li><a href="/contest/1287/my">Мои посылки</a></li> <li><a href="/contest/1287/status">Статус</a></li> <li><a href="/contest/1287/hacks">Взломы</a></li> <li><a href="/contest/1287/room/1">Комната</a></li> <li><a href="/contest/1287/standings">Положение</a></li> <li><a href="/contest/1287/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_421952b0682e0588c0bf2c6c757248ee067b5253"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E1. Дурдом (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Эта задача отличается от сложной версии только ограничением на суммарную длину ответов</span></p><p><span class="tex-font-style-bf">Это интерактивная задача</span>.</p><p>Веня приехал на экскурсию в дурдом, в котором санитары играют с пациентами в следующую игру: санитары загадывают строку $$$s$$$ длины $$$n$$$, состоящую только из строчных букв английского алфавита. Пациент может делать запросы двух типов: </p><ul> <li> <span class="tex-font-style-tt">? l r</span> — запросить все подстроки $$$s[l..r]$$$. При этом в ответе все подстроки будут перемешаны, а в каждой из подстрок будут перемешаны буквы. </li><li> <span class="tex-font-style-tt">! s</span> — сделать предположение о загаданной строке. Этот запрос нужно сделать ровно один раз, после него игра завершается. Если строка угадана, то пациент побеждает, а иначе проигрывает. </li></ul><p>Пациенту разрешено сделать <span class="tex-font-style-bf">не более $$$3$$$ запросов</span> первого типа. Чтобы игра была не так утомительна для санитаров, существует следующее ограничение: суммарно на запросы первого типа должно быть возвращено не более $$$(n+1)^2$$$ подстрок.</p><p>Помогите пациенту выиграть и выбраться из дурдома!</p><p>После запроса второго типа ваша программа должна немедленно завершиться. В случае, если ваша программа неверно угадает строку или превысит заданные ограничения на количество запросов или количество возвращенных подстрок, она получит вердикт <span class="tex-font-style-tt">Неправильный ответ</span>.</p><p>Обратите внимание, что в каждом тесте строка фиксирована и не меняется в ходе игры. Иными словами, интерактор не адаптивен.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая и единственная строка содержит число $$$n$$$ ($$$1 \le n \le 100$$$) — длину загадываемой строки.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Вы начинаете своё взаимодействие, считав $$$n$$$.</p><p>Для того, чтобы задать вопрос о подстроке с $$$l$$$ по $$$r$$$ включительно ($$$1 \le l \le r \le n$$$) выведите в отдельной строке</p><p><span class="tex-font-style-tt">? l r</span></p><p>В ответ вы получите все подстроки строки $$$s[l..r]$$$ в случайном порядке, каждую ровно один раз. В каждой из подстрок будут случайным образом перемешаны буквы. </p><p>В случае, если вы сделаете некорректный запрос, зададите более $$$3$$$ запросов данного типа, или в результате заданных запросов Вам будет возвращено суммарно более $$$(n+1)^2$$$ подстрок, то ваше решение получит вердикт <span class="tex-font-style-bf">Неправильный ответ</span>.</p><p>Для того, чтобы сделать предположение о загаданной строке $$$s$$$ выведите в отдельной строке</p><p><span class="tex-font-style-tt">! s</span></p><p>После вывода каждого запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> fflush(stdout) или cout.flush() в C++; </li><li> System.out.flush() в Java; </li><li> flush(output) в Pascal; </li><li> stdout.flush() в Python; </li><li> смотрите документацию для других языков. </li></ul><p>Если вы получили строку <span class="tex-font-style-tt">-</span> (дефис) в качестве ответа на какой-либо запрос, то вам надо завершить программу штатным образом с кодом возврата 0 (например, сделав <span class="tex-font-style-tt">exit(0)</span>). Это означает, что интерактор зафиксировал ошибку в протоколе или поведении программы. Если вы не завершите в этом случае программу штатным образом с кодом возврата 0, то можете получить любой неуспешный вердикт.</p><p><span class="tex-font-style-bf">Формат взломов</span></p><p>Для взломов используйте следующий формат:</p><p>В первой строке должно быть единственное число $$$n$$$ ($$$1 \le n \le 100$$$) — длина загадываемой строки.</p><p>Во второй строке выведите строку $$$s$$$ — сама загадываемая строка.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 a aa a cb b c c</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 2 ? 3 4 ? 4 4 ! aabc</pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'812493db1e7f9d34',t:'MTY5NjY2NTI4MS44NTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*2400"]
1287E2
1287
E2
ru
E2. Дурдом (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">E2. Дурдом (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Эта задача отличается от простой версии только ограничением на суммарную длину ответов</span></p><p><span class="tex-font-style-bf">Это интерактивная задача</span>.</p><p>Веня приехал на экскурсию в дурдом, в котором санитары играют с пациентами в следующую игру: санитары загадывают строку $$$s$$$ длины $$$n$$$, состоящую только из строчных букв английского алфавита. Пациент может делать запросы двух типов: </p><ul> <li> <span class="tex-font-style-tt">? l r</span> — запросить все подстроки $$$s[l..r]$$$. При этом в ответе все подстроки будут перемешаны, а в каждой из подстрок будут перемешаны буквы. </li><li> <span class="tex-font-style-tt">! s</span> — сделать предположение о загаданной строке. Этот запрос нужно сделать ровно один раз, после него игра завершается. Если строка угадана, то пациент побеждает, а иначе проигрывает. </li></ul><p>Пациенту разрешено сделать <span class="tex-font-style-bf">не более $$$3$$$ запросов</span> первого типа. Чтобы игра была не так утомительна для санитаров, существует следующее ограничение: суммарно на запросы первого типа должно быть возвращено не более $$$\left\lceil 0.777(n+1)^2 \right\rceil$$$ подстрок ($$$\lceil x \rceil$$$ — округление вверх числа $$$x$$$).</p><p>Помогите пациенту выиграть и выбраться из дурдома!</p><p>После запроса второго типа ваша программа должна немедленно завершиться. В случае, если ваша программа неверно угадает строку или превысит заданные ограничения на количество запросов или количество возвращенных подстрок, она получит вердикт <span class="tex-font-style-tt">Неправильный ответ</span>.</p><p>Обратите внимание, что в каждом тесте строка фиксирована и не меняется в ходе игры. Иными словами, интерактор не адаптивен.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая и единственная строка содержит число $$$n$$$ ($$$1 \le n \le 100$$$) — длину загадываемой строки.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Вы начинаете своё взаимодействие, считав $$$n$$$.</p><p>Для того, чтобы задать вопрос о подстроке с $$$l$$$ по $$$r$$$ включительно ($$$1 \le l \le r \le n$$$) выведите в отдельной строке</p><p><span class="tex-font-style-tt">? l r</span></p><p>В ответ вы получите все подстроки строки $$$s[l..r]$$$ в случайном порядке, каждую ровно один раз. В каждой из подстрок будут случайным образом перемешаны буквы. </p><p>В случае, если вы сделаете некорректный запрос, зададите более $$$3$$$ запросов данного типа, или в результате заданных запросов Вам будет возвращено суммарно более $$$\left\lceil 0.777(n+1)^2 \right\rceil$$$ подстрок, то ваше решение получит вердикт <span class="tex-font-style-bf">Неправильный ответ</span>.</p><p>Для того, чтобы сделать предположение о загаданной строке $$$s$$$ выведите в отдельной строке</p><p><span class="tex-font-style-tt">! s</span></p><p>После вывода каждого запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> fflush(stdout) или cout.flush() в C++; </li><li> System.out.flush() в Java; </li><li> flush(output) в Pascal; </li><li> stdout.flush() в Python; </li><li> смотрите документацию для других языков. </li></ul><p>Если вы получили строку <span class="tex-font-style-tt">-</span> (дефис) в качестве ответа на какой-либо запрос, то вам надо завершить программу штатным образом с кодом возврата 0 (например, сделав <span class="tex-font-style-tt">exit(0)</span>). Это означает, что интерактор зафиксировал ошибку в протоколе или поведении программы. Если вы не завершите в этом случае программу штатным образом с кодом возврата 0, то можете получить любой неуспешный вердикт.</p><p><span class="tex-font-style-bf">Формат взломов.</span></p><p>Для взломов используйте следующий формат:</p><p>В первой строке должно быть единственное число $$$n$$$ ($$$1 \le n \le 100$$$) — длина загадываемой строки.</p><p>Во второй строке выведите строку $$$s$$$ – сама загадываемая строка.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 a aa a cb b c c</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 2 ? 3 4 ? 4 4 ! aabc</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="ddb6fda43c56ad64836bdf342d4c7b41"/> <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="a3f727fbd8fb1cd5fd13bd2927088ade7af51ba9"/> <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='ddb6fda43c56ad64836bdf342d4c7b41'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1287%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='ddb6fda43c56ad64836bdf342d4c7b41'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1287">Codeforces Round 612 (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='ddb6fda43c56ad64836bdf342d4c7b41'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1287/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ddb6fda43c56ad64836bdf342d4c7b41'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509651"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ddb6fda43c56ad64836bdf342d4c7b41'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509651"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10242:10243" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10251" resourceName="Codeforces Round #612 - 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/1287">Задачи</a></li> <li><a href="/contest/1287/submit">Отослать</a></li> <li><a href="/contest/1287/my">Мои посылки</a></li> <li><a href="/contest/1287/status">Статус</a></li> <li><a href="/contest/1287/hacks">Взломы</a></li> <li><a href="/contest/1287/room/1">Комната</a></li> <li><a href="/contest/1287/standings">Положение</a></li> <li><a href="/contest/1287/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_02261d854cfc995935fed320e4e3381dedc2e227"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Эта задача отличается от простой версии только ограничением на суммарную длину ответов</span></p><p><span class="tex-font-style-bf">Это интерактивная задача</span>.</p><p>Веня приехал на экскурсию в дурдом, в котором санитары играют с пациентами в следующую игру: санитары загадывают строку $$$s$$$ длины $$$n$$$, состоящую только из строчных букв английского алфавита. Пациент может делать запросы двух типов: </p><ul> <li> <span class="tex-font-style-tt">? l r</span> — запросить все подстроки $$$s[l..r]$$$. При этом в ответе все подстроки будут перемешаны, а в каждой из подстрок будут перемешаны буквы. </li><li> <span class="tex-font-style-tt">! s</span> — сделать предположение о загаданной строке. Этот запрос нужно сделать ровно один раз, после него игра завершается. Если строка угадана, то пациент побеждает, а иначе проигрывает. </li></ul><p>Пациенту разрешено сделать <span class="tex-font-style-bf">не более $$$3$$$ запросов</span> первого типа. Чтобы игра была не так утомительна для санитаров, существует следующее ограничение: суммарно на запросы первого типа должно быть возвращено не более $$$\left\lceil 0.777(n+1)^2 \right\rceil$$$ подстрок ($$$\lceil x \rceil$$$ — округление вверх числа $$$x$$$).</p><p>Помогите пациенту выиграть и выбраться из дурдома!</p><p>После запроса второго типа ваша программа должна немедленно завершиться. В случае, если ваша программа неверно угадает строку или превысит заданные ограничения на количество запросов или количество возвращенных подстрок, она получит вердикт <span class="tex-font-style-tt">Неправильный ответ</span>.</p><p>Обратите внимание, что в каждом тесте строка фиксирована и не меняется в ходе игры. Иными словами, интерактор не адаптивен.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая и единственная строка содержит число $$$n$$$ ($$$1 \le n \le 100$$$) — длину загадываемой строки.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Вы начинаете своё взаимодействие, считав $$$n$$$.</p><p>Для того, чтобы задать вопрос о подстроке с $$$l$$$ по $$$r$$$ включительно ($$$1 \le l \le r \le n$$$) выведите в отдельной строке</p><p><span class="tex-font-style-tt">? l r</span></p><p>В ответ вы получите все подстроки строки $$$s[l..r]$$$ в случайном порядке, каждую ровно один раз. В каждой из подстрок будут случайным образом перемешаны буквы. </p><p>В случае, если вы сделаете некорректный запрос, зададите более $$$3$$$ запросов данного типа, или в результате заданных запросов Вам будет возвращено суммарно более $$$\left\lceil 0.777(n+1)^2 \right\rceil$$$ подстрок, то ваше решение получит вердикт <span class="tex-font-style-bf">Неправильный ответ</span>.</p><p>Для того, чтобы сделать предположение о загаданной строке $$$s$$$ выведите в отдельной строке</p><p><span class="tex-font-style-tt">! s</span></p><p>После вывода каждого запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> fflush(stdout) или cout.flush() в C++; </li><li> System.out.flush() в Java; </li><li> flush(output) в Pascal; </li><li> stdout.flush() в Python; </li><li> смотрите документацию для других языков. </li></ul><p>Если вы получили строку <span class="tex-font-style-tt">-</span> (дефис) в качестве ответа на какой-либо запрос, то вам надо завершить программу штатным образом с кодом возврата 0 (например, сделав <span class="tex-font-style-tt">exit(0)</span>). Это означает, что интерактор зафиксировал ошибку в протоколе или поведении программы. Если вы не завершите в этом случае программу штатным образом с кодом возврата 0, то можете получить любой неуспешный вердикт.</p><p><span class="tex-font-style-bf">Формат взломов.</span></p><p>Для взломов используйте следующий формат:</p><p>В первой строке должно быть единственное число $$$n$$$ ($$$1 \le n \le 100$$$) — длина загадываемой строки.</p><p>Во второй строке выведите строку $$$s$$$ – сама загадываемая строка.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 a aa a cb b c c</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 2 ? 3 4 ? 4 4 ! aabc</pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'812493e34de29da4',t:'MTY5NjY2NTI4My4xNjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*2800"]
1287F
1287
F
ru
F. ЛЧК
<div class="problem-statement"><div class="header"><div class="title">F. ЛЧК</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В Чилляндии построили бесконечно длинный Линейный Чилляндский Коллайдер (ЛЧК). К ЛЧК подсоединены $$$n$$$ труб c координатами $$$x_i$$$. В момент времени 0 из каждой трубки ЛЧК вылетает протон направо с вероятностью $$$p_i$$$ и с вероятностью $$$(1 - p_i)$$$ — влево. Протон $$$i$$$ разогнан до скорости $$$v_i$$$. Длительность эксперимента определяется как время до первого столкновения двух протонов. В случае, если столкновений не произойдет, длительность эксперимента полагается равной нулю.</p><p>Найдите математическое ожидание длительности эксперимента.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/8f71f247f9973aa84c688f02028df0fa69838ce5.png" style="max-width: 100.0%;max-height: 100.0%;"/>Иллюстрация к первому примеру</center></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ — количество труб ($$$1 \le n \le 10^5$$$). В следующих $$$n$$$ строках содержится по три целых числа $$$x_i$$$, $$$v_i$$$, $$$p_i$$$ — координата $$$i$$$-й трубы, скорость $$$i$$$-го протона, и вероятность вылета $$$i$$$-го протона вправо в процентах ($$$-10^9 \le x_i \le 10^9, 1 \le v \le 10^6, 0 \le p_i \le 100$$$). Гарантируется, что все $$$x_i$$$ различны и отсортированы в порядке возрастания.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Можно показать, что ответ всегда можно представить в виде дроби $$$P/Q$$$, где $$$P$$$ — целое число, а $$$Q$$$ — натуральное число, не кратное $$$998\,244\,353$$$. В таком случае выведите $$$P \cdot Q^{-1}$$$ по модулю $$$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> 2 1 1 100 3 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 7 10 0 9 4 86 14 5 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 6 4 50 11 25 50 13 16 50 15 8 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 150902884 </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="0c2905404827a813d5f58f9a4fc41a72"/> <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="a3f727fbd8fb1cd5fd13bd2927088ade7af51ba9"/> <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='0c2905404827a813d5f58f9a4fc41a72'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1287%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='0c2905404827a813d5f58f9a4fc41a72'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1287">Codeforces Round 612 (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='0c2905404827a813d5f58f9a4fc41a72'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1287/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др."> теория вероятностей </span> </div> <div class="roundbox borderTopRound 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='0c2905404827a813d5f58f9a4fc41a72'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="509652"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0c2905404827a813d5f58f9a4fc41a72'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="509652"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/72809" title="Codeforces Round #612" target="_blank">Codeforces Round #612</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10242:10243" 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/72867" title="Codeforces Round #612 - Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10251" resourceName="Codeforces Round #612 - 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/1287">Задачи</a></li> <li><a href="/contest/1287/submit">Отослать</a></li> <li><a href="/contest/1287/my">Мои посылки</a></li> <li><a href="/contest/1287/status">Статус</a></li> <li><a href="/contest/1287/hacks">Взломы</a></li> <li><a href="/contest/1287/room/1">Комната</a></li> <li><a href="/contest/1287/standings">Положение</a></li> <li><a href="/contest/1287/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e7b56a5e9f6af308edb0516fb2442b0f167cfff3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. ЛЧК</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В Чилляндии построили бесконечно длинный Линейный Чилляндский Коллайдер (ЛЧК). К ЛЧК подсоединены $$$n$$$ труб c координатами $$$x_i$$$. В момент времени 0 из каждой трубки ЛЧК вылетает протон направо с вероятностью $$$p_i$$$ и с вероятностью $$$(1 - p_i)$$$ — влево. Протон $$$i$$$ разогнан до скорости $$$v_i$$$. Длительность эксперимента определяется как время до первого столкновения двух протонов. В случае, если столкновений не произойдет, длительность эксперимента полагается равной нулю.</p><p>Найдите математическое ожидание длительности эксперимента.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/8f71f247f9973aa84c688f02028df0fa69838ce5.png" style="max-width: 100.0%;max-height: 100.0%;" />Иллюстрация к первому примеру</center></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ — количество труб ($$$1 \le n \le 10^5$$$). В следующих $$$n$$$ строках содержится по три целых числа $$$x_i$$$, $$$v_i$$$, $$$p_i$$$ — координата $$$i$$$-й трубы, скорость $$$i$$$-го протона, и вероятность вылета $$$i$$$-го протона вправо в процентах ($$$-10^9 \le x_i \le 10^9, 1 \le v \le 10^6, 0 \le p_i \le 100$$$). Гарантируется, что все $$$x_i$$$ различны и отсортированы в порядке возрастания.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Можно показать, что ответ всегда можно представить в виде дроби $$$P/Q$$$, где $$$P$$$ — целое число, а $$$Q$$$ — натуральное число, не кратное $$$998\,244\,353$$$. В таком случае выведите $$$P \cdot Q^{-1}$$$ по модулю $$$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> 2 1 1 100 3 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 7 10 0 9 4 86 14 5 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 6 4 50 11 25 50 13 16 50 15 8 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 150902884 </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:54: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:'812493eb7a379d3a',t:'MTY5NjY2NTI4NC40OTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\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.", "\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"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*3100"]
1288A
1288
A
ru
A. Дедлайн
<div class="problem-statement"><div class="header"><div class="title">A. Дедлайн</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Адилбеку назначили особый проект. Для Адилбека это означает, что у него есть $$$n$$$ дней, чтобы запустить особую программу и представить полученные результаты. Но есть одна проблема: программе нужно работать $$$d$$$ дней, чтобы посчитать результаты.</p><p>К счастью, Адилбек может оптимизировать программу. Если он потратит $$$x$$$ ($$$x$$$ — целое неотрицательное) дней на оптимизацию, то программа станет работать за $$$\left\lceil \frac{d}{x + 1} \right\rceil$$$ дней ($$$\left\lceil a \right\rceil$$$ — это округление вверх: $$$\left\lceil 2.4 \right\rceil = 3$$$, $$$\left\lceil 2 \right\rceil = 2$$$). Программу не получится оптимизировать, пока она работает, а потому общее количество потраченных Адилбеком дней будет равняться $$$x + \left\lceil \frac{d}{x + 1} \right\rceil$$$.</p><p>Успеет ли Адилбек получить результаты за не более, чем $$$n$$$ дней?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$T$$$ ($$$1 \le T \le 50$$$) — количество наборов входных данных.</p><p>В следующих $$$T$$$ строках заданы сами наборы – по одному в строке. Каждая строка содержит два целых числа $$$n$$$ и $$$d$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le d \le 10^9$$$) — количество дней перед дедлайном и количество дней, за которое отрабатывает программа.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$T$$$ ответов — по одному на набор входных данных. Для каждого набора выведите <span class="tex-font-style-tt">YES</span> (регистр не важен), если Адилбек сможет уложиться в $$$n$$$ дней или <span class="tex-font-style-tt">NO</span> (регистр не важен) в противном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 4 5 5 11 </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>В первом наборе, Адилбек решает совсем не оптимизировать программу, так как $$$d \le n$$$.</p><p>Во втором наборе, Адилбек может потратить $$$1$$$ день на оптимизацию и программа станет отрабатывать за $$$\left\lceil \frac{5}{2} \right\rceil = 3$$$ дней. Суммарно, он потратит $$$4$$$ дня и уложится в сроки.</p><p>В третьем наборе, невозможно уложиться в сроки. Например, если Адилбек потратит $$$2$$$ дня на оптимизацию, то программа все равно будет работать еще $$$\left\lceil \frac{11}{2+1} \right\rceil = 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="4ae53b70b64d27e3daecd8f6f0f957c7"/> <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="cfb4a73cfbd8c8911da982a0efc03cb53abd4d9e"/> <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='4ae53b70b64d27e3daecd8f6f0f957c7'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1288%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='4ae53b70b64d27e3daecd8f6f0f957c7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1288">Educational Codeforces Round 80 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='4ae53b70b64d27e3daecd8f6f0f957c7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1288/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Тернарный поиск"> тернарный поиск </span> </div> <div class="roundbox borderTopRound 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='4ae53b70b64d27e3daecd8f6f0f957c7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="516087"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4ae53b70b64d27e3daecd8f6f0f957c7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="516087"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73061" title="73061" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="18394:18395" 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/73105" title="Разбор Educational Codeforces Round 80" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10603:10604" 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/1288">Задачи</a></li> <li><a href="/contest/1288/submit">Отослать</a></li> <li><a href="/contest/1288/my">Мои посылки</a></li> <li><a href="/contest/1288/status">Статус</a></li> <li><a href="/contest/1288/hacks">Взломы</a></li> <li><a href="/contest/1288/standings">Положение</a></li> <li><a href="/contest/1288/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_3c2b9ef53c62db353fc26353c36f915c4c11d5a2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Дедлайн</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Адилбеку назначили особый проект. Для Адилбека это означает, что у него есть $$$n$$$ дней, чтобы запустить особую программу и представить полученные результаты. Но есть одна проблема: программе нужно работать $$$d$$$ дней, чтобы посчитать результаты.</p><p>К счастью, Адилбек может оптимизировать программу. Если он потратит $$$x$$$ ($$$x$$$ — целое неотрицательное) дней на оптимизацию, то программа станет работать за $$$\left\lceil \frac{d}{x + 1} \right\rceil$$$ дней ($$$\left\lceil a \right\rceil$$$ — это округление вверх: $$$\left\lceil 2.4 \right\rceil = 3$$$, $$$\left\lceil 2 \right\rceil = 2$$$). Программу не получится оптимизировать, пока она работает, а потому общее количество потраченных Адилбеком дней будет равняться $$$x + \left\lceil \frac{d}{x + 1} \right\rceil$$$.</p><p>Успеет ли Адилбек получить результаты за не более, чем $$$n$$$ дней?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$T$$$ ($$$1 \le T \le 50$$$) — количество наборов входных данных.</p><p>В следующих $$$T$$$ строках заданы сами наборы – по одному в строке. Каждая строка содержит два целых числа $$$n$$$ и $$$d$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le d \le 10^9$$$) — количество дней перед дедлайном и количество дней, за которое отрабатывает программа.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$T$$$ ответов — по одному на набор входных данных. Для каждого набора выведите <span class="tex-font-style-tt">YES</span> (регистр не важен), если Адилбек сможет уложиться в $$$n$$$ дней или <span class="tex-font-style-tt">NO</span> (регистр не важен) в противном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 4 5 5 11 </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>В первом наборе, Адилбек решает совсем не оптимизировать программу, так как $$$d \le n$$$.</p><p>Во втором наборе, Адилбек может потратить $$$1$$$ день на оптимизацию и программа станет отрабатывать за $$$\left\lceil \frac{5}{2} \right\rceil = 3$$$ дней. Суммарно, он потратит $$$4$$$ дня и уложится в сроки.</p><p>В третьем наборе, невозможно уложиться в сроки. Например, если Адилбек потратит $$$2$$$ дня на оптимизацию, то программа все равно будет работать еще $$$\left\lceil \frac{11}{2+1} \right\rceil = 4$$$ дня.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:54: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:'812493f3ceed9d61',t:'MTY5NjY2NTI4Ni4wNTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0422\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "*1100"]
1288B
1288
B
ru
B. Очередная мемная задача
<div class="problem-statement"><div class="header"><div class="title">B. Очередная мемная задача</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам заданы два числа $$$A$$$ и $$$B$$$, посчитайте количество пар $$$(a, b)$$$, таких, что $$$1 \le a \le A$$$, $$$1 \le b \le B$$$, и равенство $$$a \cdot b + a + b = conc(a, b)$$$ верно; $$$conc(a, b)$$$ — это операция конкатенации $$$a$$$ и $$$b$$$ (например, $$$conc(12, 23) = 1223$$$, $$$conc(100, 11) = 10011$$$). <span class="tex-font-style-bf">Ни $$$a$$$, ни $$$b$$$ не должны содержать лидирующих нулей</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных содержит два числа $$$A$$$ и $$$B$$$ $$$(1 \le A, B \le 10^9)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите одно число — количество пар $$$(a, b)$$$, таких, что $$$1 \le a \le A$$$, $$$1 \le b \le B$$$, и равенство $$$a \cdot b + a + b = conc(a, b)$$$ верно.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre><div class="test-example-line test-example-line-even test-example-line-0">3</div><div class="test-example-line test-example-line-odd test-example-line-1">1 11</div><div class="test-example-line test-example-line-even test-example-line-2">4 2</div><div class="test-example-line test-example-line-odd test-example-line-3">191 31415926</div></pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 0 1337 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В пером наборе входных данных есть только одна подходящая пара: $$$a = 1$$$, $$$b = 9$$$ ($$$1 + 9 + 1 \cdot 9 = 19$$$).</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="acee73f1f89131d34a059c2d3c77d2f7"/> <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="cfb4a73cfbd8c8911da982a0efc03cb53abd4d9e"/> <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='acee73f1f89131d34a059c2d3c77d2f7'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1288%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='acee73f1f89131d34a059c2d3c77d2f7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1288">Educational Codeforces Round 80 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='acee73f1f89131d34a059c2d3c77d2f7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1288/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='acee73f1f89131d34a059c2d3c77d2f7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="516088"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='acee73f1f89131d34a059c2d3c77d2f7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="516088"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73061" title="73061" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="18394:18395" 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/73105" title="Разбор Educational Codeforces Round 80" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10603:10604" 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/1288">Задачи</a></li> <li><a href="/contest/1288/submit">Отослать</a></li> <li><a href="/contest/1288/my">Мои посылки</a></li> <li><a href="/contest/1288/status">Статус</a></li> <li><a href="/contest/1288/hacks">Взломы</a></li> <li><a href="/contest/1288/standings">Положение</a></li> <li><a href="/contest/1288/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e19c253572694c6c78b87178ac0d8c8449dd54a0"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Очередная мемная задача</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам заданы два числа $$$A$$$ и $$$B$$$, посчитайте количество пар $$$(a, b)$$$, таких, что $$$1 \le a \le A$$$, $$$1 \le b \le B$$$, и равенство $$$a \cdot b + a + b = conc(a, b)$$$ верно; $$$conc(a, b)$$$ — это операция конкатенации $$$a$$$ и $$$b$$$ (например, $$$conc(12, 23) = 1223$$$, $$$conc(100, 11) = 10011$$$). <span class="tex-font-style-bf">Ни $$$a$$$, ни $$$b$$$ не должны содержать лидирующих нулей</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных содержит два числа $$$A$$$ и $$$B$$$ $$$(1 \le A, B \le 10^9)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите одно число — количество пар $$$(a, b)$$$, таких, что $$$1 \le a \le A$$$, $$$1 \le b \le B$$$, и равенство $$$a \cdot b + a + b = conc(a, b)$$$ верно.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre><div class="test-example-line test-example-line-even test-example-line-0">3</div><div class="test-example-line test-example-line-odd test-example-line-1">1 11</div><div class="test-example-line test-example-line-even test-example-line-2">4 2</div><div class="test-example-line test-example-line-odd test-example-line-3">191 31415926</div></pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 0 1337 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В пером наборе входных данных есть только одна подходящая пара: $$$a = 1$$$, $$$b = 9$$$ ($$$1 + 9 + 1 \cdot 9 = 19$$$).</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:54: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:'812493fd88dd3a83',t:'MTY5NjY2NTI4Ny4zNzcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1288C
1288
C
ru
C. Два массива
<div class="problem-statement"><div class="header"><div class="title">C. Два массива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам заданы два числа $$$n$$$ и $$$m$$$. Посчитайте количество таких пар массивов $$$(a, b)$$$, что:</p><ul> <li> длина обоих массивов равна $$$m$$$; </li><li> каждый элемент каждого массива — целое число от $$$1$$$ до $$$n$$$ (включительно); </li><li> $$$a_i \le b_i$$$ для любого индекса $$$i$$$ от $$$1$$$ до $$$m$$$; </li><li> массив $$$a$$$ отсортирован в порядке неубывания; </li><li> массив $$$b$$$ отсортирован в порядке невозрастания. </li></ul><p>Так как ответ может быть слишком большим, посчитайте его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит два числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 1000$$$, $$$1 \le m \le 10$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число – количество массивов $$$a$$$ и $$$b$$$, удовлетворяющих условиям, описанным выше по модулю $$$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> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 55 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 723 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 157557417 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте существуют $$$5$$$ подходящих вариантов: </p><ul> <li> $$$a = [1, 1], b = [2, 2]$$$; </li><li> $$$a = [1, 2], b = [2, 2]$$$; </li><li> $$$a = [2, 2], b = [2, 2]$$$; </li><li> $$$a = [1, 1], b = [2, 1]$$$; </li><li> $$$a = [1, 1], b = [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="b64363f661ce5630441711d6ebc7bd4b"/> <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="cfb4a73cfbd8c8911da982a0efc03cb53abd4d9e"/> <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='b64363f661ce5630441711d6ebc7bd4b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1288%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='b64363f661ce5630441711d6ebc7bd4b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1288">Educational Codeforces Round 80 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='b64363f661ce5630441711d6ebc7bd4b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1288/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound 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='b64363f661ce5630441711d6ebc7bd4b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="516089"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b64363f661ce5630441711d6ebc7bd4b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="516089"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73061" title="73061" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="18394:18395" 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/73105" title="Разбор Educational Codeforces Round 80" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10603:10604" 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/1288">Задачи</a></li> <li><a href="/contest/1288/submit">Отослать</a></li> <li><a href="/contest/1288/my">Мои посылки</a></li> <li><a href="/contest/1288/status">Статус</a></li> <li><a href="/contest/1288/hacks">Взломы</a></li> <li><a href="/contest/1288/standings">Положение</a></li> <li><a href="/contest/1288/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_929dad1292914df770682abb3ef56f78d07ce85b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Два массива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам заданы два числа $$$n$$$ и $$$m$$$. Посчитайте количество таких пар массивов $$$(a, b)$$$, что:</p><ul> <li> длина обоих массивов равна $$$m$$$; </li><li> каждый элемент каждого массива — целое число от $$$1$$$ до $$$n$$$ (включительно); </li><li> $$$a_i \le b_i$$$ для любого индекса $$$i$$$ от $$$1$$$ до $$$m$$$; </li><li> массив $$$a$$$ отсортирован в порядке неубывания; </li><li> массив $$$b$$$ отсортирован в порядке невозрастания. </li></ul><p>Так как ответ может быть слишком большим, посчитайте его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит два числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 1000$$$, $$$1 \le m \le 10$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число – количество массивов $$$a$$$ и $$$b$$$, удовлетворяющих условиям, описанным выше по модулю $$$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> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 55 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 723 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 157557417 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте существуют $$$5$$$ подходящих вариантов: </p><ul> <li> $$$a = [1, 1], b = [2, 2]$$$; </li><li> $$$a = [1, 2], b = [2, 2]$$$; </li><li> $$$a = [2, 2], b = [2, 2]$$$; </li><li> $$$a = [1, 1], b = [2, 1]$$$; </li><li> $$$a = [1, 1], b = [1, 1]$$$. </li></ul></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:54: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:'81249405cc371640',t:'MTY5NjY2NTI4OC43MzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1600"]
1288D
1288
D
ru
D. Задача Минимакс
<div class="problem-statement"><div class="header"><div class="title">D. Задача Минимакс</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам заданы $$$n$$$ массивов $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$; каждый массив состоит ровно из $$$m$$$ целых чисел. Будем обозначать $$$y$$$-й элемент $$$x$$$-го массива как $$$a_{x, y}$$$.</p><p>Вы должны выбрать два массива $$$a_i$$$ и $$$a_j$$$ ($$$1 \le i, j \le n$$$, допустима ситуация $$$i = j$$$). Из данных массивов строится новый массив $$$b$$$ длины $$$m$$$, такой что для каждого $$$k \in [1, m]$$$ $$$b_k = \max(a_{i, k}, a_{j, k})$$$.</p><p>Ваша задача — выбрать $$$i$$$ и $$$j$$$ так, чтобы значение $$$\min \limits_{k = 1}^{m} b_k$$$ было максимально возможным.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$, $$$1 \le m \le 8$$$) — количество массивов и количество элементов в каждом массиве соответственно.</p><p>Далее следуют $$$n$$$ строк, в $$$x$$$-й строке задан массив $$$a_x$$$, другими словами, $$$m$$$ целых чисел $$$a_{x, 1}$$$, $$$a_{x, 2}$$$, ..., $$$a_{x, m}$$$ ($$$0 \le a_{x, y} \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два числа $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$, <span class="tex-font-style-bf">допустима ситуация $$$i = j$$$</span>) — индексы выбранных массивов, таких что значение $$$\min \limits_{k = 1}^{m} b_k$$$ — максимально возможное. Если существует несколько ответов — выведите любой из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 5 5 0 3 1 2 1 8 9 1 3 1 2 3 4 5 9 1 0 3 7 2 3 0 6 3 6 4 1 7 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 5 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="f5b364097718c3f198e6429722667cff"/> <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="cfb4a73cfbd8c8911da982a0efc03cb53abd4d9e"/> <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='f5b364097718c3f198e6429722667cff'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1288%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='f5b364097718c3f198e6429722667cff'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1288">Educational Codeforces Round 80 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='f5b364097718c3f198e6429722667cff'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1288/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound 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='f5b364097718c3f198e6429722667cff'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="516090"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f5b364097718c3f198e6429722667cff'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="516090"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73061" title="73061" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="18394:18395" 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/73105" title="Разбор Educational Codeforces Round 80" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10603:10604" 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/1288">Задачи</a></li> <li><a href="/contest/1288/submit">Отослать</a></li> <li><a href="/contest/1288/my">Мои посылки</a></li> <li><a href="/contest/1288/status">Статус</a></li> <li><a href="/contest/1288/hacks">Взломы</a></li> <li><a href="/contest/1288/standings">Положение</a></li> <li><a href="/contest/1288/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_83b4014df3a0008006042c04884aab464d50b1b0"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Задача Минимакс</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам заданы $$$n$$$ массивов $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$; каждый массив состоит ровно из $$$m$$$ целых чисел. Будем обозначать $$$y$$$-й элемент $$$x$$$-го массива как $$$a_{x, y}$$$.</p><p>Вы должны выбрать два массива $$$a_i$$$ и $$$a_j$$$ ($$$1 \le i, j \le n$$$, допустима ситуация $$$i = j$$$). Из данных массивов строится новый массив $$$b$$$ длины $$$m$$$, такой что для каждого $$$k \in [1, m]$$$ $$$b_k = \max(a_{i, k}, a_{j, k})$$$.</p><p>Ваша задача — выбрать $$$i$$$ и $$$j$$$ так, чтобы значение $$$\min \limits_{k = 1}^{m} b_k$$$ было максимально возможным.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$, $$$1 \le m \le 8$$$) — количество массивов и количество элементов в каждом массиве соответственно.</p><p>Далее следуют $$$n$$$ строк, в $$$x$$$-й строке задан массив $$$a_x$$$, другими словами, $$$m$$$ целых чисел $$$a_{x, 1}$$$, $$$a_{x, 2}$$$, ..., $$$a_{x, m}$$$ ($$$0 \le a_{x, y} \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два числа $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$, <span class="tex-font-style-bf">допустима ситуация $$$i = j$$$</span>) — индексы выбранных массивов, таких что значение $$$\min \limits_{k = 1}^{m} b_k$$$ — максимально возможное. Если существует несколько ответов — выведите любой из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 5 5 0 3 1 2 1 8 9 1 3 1 2 3 4 5 9 1 0 3 7 2 3 0 6 3 6 4 1 7 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 5 </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:54: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:'8124940e68d01622',t:'MTY5NjY2NTI5MC4xMjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\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", "\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "*2000"]
1288E
1288
E
ru
E. Симулятор мессенджера
<div class="problem-statement"><div class="header"><div class="title">E. Симулятор мессенджера</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп — частый пользователь одного очень популярного мессенджера. Он постоянно общается со своими друзьями. У него есть $$$n$$$ друзей, пронумерованных от $$$1$$$ до $$$n$$$.</p><p>Напомним, что перестановка размера $$$n$$$ — это такой массив размера $$$n$$$, что каждое число от $$$1$$$ до $$$n$$$ встречается в нем ровно один раз.</p><p>Так что его список последних диалогов может быть представлен в виде перестановки $$$p$$$ размера $$$n$$$. $$$p_1$$$ — это самые недавний диалог, $$$p_2$$$ — второй по давности и так далее.</p><p>Изначально список диалогов Поликарпа $$$p$$$ выглядит как $$$1, 2, \dots, n$$$ (другими словами, является тождественной перестановкой).</p><p>После этого он получает $$$m$$$ сообщений, $$$j$$$-е сообщение приходит от друга $$$a_j$$$. Тогда друг $$$a_j$$$ перемещается на первую позицию в перестановке, сдвигая всех между первой позицией и текущей позицией $$$a_j$$$ на $$$1$$$. Обратите внимание, что если друг $$$a_j$$$ уже стоит на первой позиции, то ничего не происходит.</p><p>Например, пусть список последних диалогов будет $$$p = [4, 1, 5, 3, 2]$$$: </p><ul> <li> если он получает сообщение от друга $$$3$$$, то $$$p$$$ становится $$$[3, 4, 1, 5, 2]$$$; </li><li> если он получает сообщение от друга $$$4$$$, то $$$p$$$ не меняется $$$[4, 1, 5, 3, 2]$$$; </li><li> если он получает сообщение от друга $$$2$$$, то $$$p$$$ становится $$$[2, 4, 1, 5, 3]$$$. </li></ul><p>Для каждого друга рассмотрим, на каких позициях он был в самом начале и после получения каждого сообщения. Поликарп хочет знать, какие были минимальная и максимальная позиции.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 3 \cdot 10^5$$$) — количество друзей Поликарпа и количество полученных сообщений, соответственно.</p><p>Во второй строке записаны $$$m$$$ целых чисел $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_i \le n$$$) — описания полученных сообщений.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ пар целых чисел. Для каждого друга выведите минимальную и максимальную позиции, на которых он был в самом начале и после получения каждого сообщения.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 3 5 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 2 5 1 4 1 5 1 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 1 2 3 4 1 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере список последних диалогов Поликарпа выглядит так: </p><ul> <li> $$$[1, 2, 3, 4, 5]$$$ </li><li> $$$[3, 1, 2, 4, 5]$$$ </li><li> $$$[5, 3, 1, 2, 4]$$$ </li><li> $$$[1, 5, 3, 2, 4]$$$ </li><li> $$$[4, 1, 5, 3, 2]$$$ </li></ul><p>Так что, например, позиции друга $$$2$$$ — $$$2, 3, 4, 4, 5$$$, соответственно. Из всех них $$$2$$$ — это минимум, а $$$5$$$ — это максимум. Поэтому ответ для друга $$$2$$$ — это пара $$$(2, 5)$$$.</p><p>Во втором примере список последних диалогов Поликарпа выглядит так: </p><ul> <li> $$$[1, 2, 3, 4]$$$ </li><li> $$$[1, 2, 3, 4]$$$ </li><li> $$$[2, 1, 3, 4]$$$ </li><li> $$$[4, 2, 1, 3]$$$ </li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="bbb1741cbc47eac77a086a68b2df88c5"/> <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="cfb4a73cfbd8c8911da982a0efc03cb53abd4d9e"/> <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='bbb1741cbc47eac77a086a68b2df88c5'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1288%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='bbb1741cbc47eac77a086a68b2df88c5'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1288">Educational Codeforces Round 80 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='bbb1741cbc47eac77a086a68b2df88c5'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1288/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='bbb1741cbc47eac77a086a68b2df88c5'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="516091"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bbb1741cbc47eac77a086a68b2df88c5'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="516091"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73061" title="73061" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="18394:18395" 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/73105" title="Разбор Educational Codeforces Round 80" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10603:10604" 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/1288">Задачи</a></li> <li><a href="/contest/1288/submit">Отослать</a></li> <li><a href="/contest/1288/my">Мои посылки</a></li> <li><a href="/contest/1288/status">Статус</a></li> <li><a href="/contest/1288/hacks">Взломы</a></li> <li><a href="/contest/1288/standings">Положение</a></li> <li><a href="/contest/1288/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c0af998858456d42e329404f02620876f4606148"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Симулятор мессенджера</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп — частый пользователь одного очень популярного мессенджера. Он постоянно общается со своими друзьями. У него есть $$$n$$$ друзей, пронумерованных от $$$1$$$ до $$$n$$$.</p><p>Напомним, что перестановка размера $$$n$$$ — это такой массив размера $$$n$$$, что каждое число от $$$1$$$ до $$$n$$$ встречается в нем ровно один раз.</p><p>Так что его список последних диалогов может быть представлен в виде перестановки $$$p$$$ размера $$$n$$$. $$$p_1$$$ — это самые недавний диалог, $$$p_2$$$ — второй по давности и так далее.</p><p>Изначально список диалогов Поликарпа $$$p$$$ выглядит как $$$1, 2, \dots, n$$$ (другими словами, является тождественной перестановкой).</p><p>После этого он получает $$$m$$$ сообщений, $$$j$$$-е сообщение приходит от друга $$$a_j$$$. Тогда друг $$$a_j$$$ перемещается на первую позицию в перестановке, сдвигая всех между первой позицией и текущей позицией $$$a_j$$$ на $$$1$$$. Обратите внимание, что если друг $$$a_j$$$ уже стоит на первой позиции, то ничего не происходит.</p><p>Например, пусть список последних диалогов будет $$$p = [4, 1, 5, 3, 2]$$$: </p><ul> <li> если он получает сообщение от друга $$$3$$$, то $$$p$$$ становится $$$[3, 4, 1, 5, 2]$$$; </li><li> если он получает сообщение от друга $$$4$$$, то $$$p$$$ не меняется $$$[4, 1, 5, 3, 2]$$$; </li><li> если он получает сообщение от друга $$$2$$$, то $$$p$$$ становится $$$[2, 4, 1, 5, 3]$$$. </li></ul><p>Для каждого друга рассмотрим, на каких позициях он был в самом начале и после получения каждого сообщения. Поликарп хочет знать, какие были минимальная и максимальная позиции.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 3 \cdot 10^5$$$) — количество друзей Поликарпа и количество полученных сообщений, соответственно.</p><p>Во второй строке записаны $$$m$$$ целых чисел $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_i \le n$$$) — описания полученных сообщений.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ пар целых чисел. Для каждого друга выведите минимальную и максимальную позиции, на которых он был в самом начале и после получения каждого сообщения.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 3 5 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 2 5 1 4 1 5 1 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 1 2 3 4 1 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере список последних диалогов Поликарпа выглядит так: </p><ul> <li> $$$[1, 2, 3, 4, 5]$$$ </li><li> $$$[3, 1, 2, 4, 5]$$$ </li><li> $$$[5, 3, 1, 2, 4]$$$ </li><li> $$$[1, 5, 3, 2, 4]$$$ </li><li> $$$[4, 1, 5, 3, 2]$$$ </li></ul><p>Так что, например, позиции друга $$$2$$$ — $$$2, 3, 4, 4, 5$$$, соответственно. Из всех них $$$2$$$ — это минимум, а $$$5$$$ — это максимум. Поэтому ответ для друга $$$2$$$ — это пара $$$(2, 5)$$$.</p><p>Во втором примере список последних диалогов Поликарпа выглядит так: </p><ul> <li> $$$[1, 2, 3, 4]$$$ </li><li> $$$[1, 2, 3, 4]$$$ </li><li> $$$[2, 1, 3, 4]$$$ </li><li> $$$[4, 2, 1, 3]$$$ </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:54: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:'812494170cc67b6b',t:'MTY5NjY2NTI5MS40NjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2000"]
1288F
1288
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>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_2$$$ вершин, а также в графе $$$m$$$ ребер. <span class="tex-font-style-bf">Граф может содержать кратные ребра</span>.</p><p>Первоначально, все ребра графа бесцветные. Каждое ребро вы можете либо оставить бесцветным (это бесплатно), либо покрасить в красный (стоимость данного действия $$$r$$$ монет), либо покрасить в синий (за $$$b$$$ монет). Никакое ребро не может быть покрашено в оба цвета одновременно.</p><p>Также в графе вершины разбиваются на три типа — бесцветные, красные и синие. Цветные вершины добавляют дополнительные ограничения на раскраску ребер:</p><ul> <li> у каждой красной вершины количество смежных с ней красных ребер должно быть <span class="tex-font-style-bf">строго больше</span>, чем смежных с ней синих ребер; </li><li> у каждой синей вершины количество смежных с ней синих ребер должно быть <span class="tex-font-style-bf">строго больше</span>, чем смежных с ней красных ребер. </li></ul><p>Бесцветные вершины не накладывают никаких ограничений.</p><p>Ваша задача — раскрасить некоторые (возможно, никакие) ребра так, чтобы выполнялись заданные ограничения, и среди всех возможных раскрасок выбрать такую, суммарная стоимость которой минимальна. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы пять целых чисел $$$n_1$$$, $$$n_2$$$, $$$m$$$, $$$r$$$ и $$$b$$$ ($$$1 \le n_1, n_2, m, r, b \le 200$$$) — количество вершин в первой доле, количество вершин во второй доле, количество ребер, стоимость покраски одного ребра в красный и стоимость покраски в синий соответственно.</p><p>Во второй строке задана одна строка из $$$n_1$$$ символов. Каждый символ — это <span class="tex-font-style-tt">U</span>, <span class="tex-font-style-tt">R</span> или <span class="tex-font-style-tt">B</span>. Если $$$i$$$-й символ — это <span class="tex-font-style-tt">U</span>, то $$$i$$$-я вершина первой доли бесцветная; <span class="tex-font-style-tt">R</span> соответствует красной вершине, а <span class="tex-font-style-tt">B</span> — синей вершине.</p><p>В третьей строке задана строка из $$$n_2$$$ символов. Каждый символ — это также <span class="tex-font-style-tt">U</span>, <span class="tex-font-style-tt">R</span> или <span class="tex-font-style-tt">B</span>. Данная строка задает цвета вершин второй доли аналогичным образом.</p><p>Далее следуют $$$m$$$ строк: в $$$i$$$-й строке заданы два целых числа $$$u_i$$$ и $$$v_i$$$ ($$$1 \le u_i \le n_1$$$, $$$1 \le v_i \le n_2$$$), задающие ребро между вершиной $$$u_i$$$ из первой доли и вершиной $$$v_i$$$ из второй доли.</p><p>Граф может содержать кратные ребра.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если не существует раскраски ребер, которая удовлетворяет всем заданным ограничениям, — выведите $$$-1$$$.</p><p>Иначе, выведите число $$$c$$$, обозначающее минимальную суммарную стоимость раскраски, и строку из $$$m$$$ символов. $$$i$$$-й символ должен быть <span class="tex-font-style-tt">U</span>, если $$$i$$$-е ребро осталось бесцветным, <span class="tex-font-style-tt">R</span>, если $$$i$$$-е ребро покрашено в красный, или <span class="tex-font-style-tt">B</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> 3 2 6 10 15 RRB UB 3 2 2 2 1 2 1 1 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 35 BUURRU </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 3 4 5 RRR B 2 1 1 1 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 3 4 5 URU B 2 1 1 1 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 14 RBB </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="6094ad8ab496796f35fd8b18068a7cc8"/> <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="cfb4a73cfbd8c8911da982a0efc03cb53abd4d9e"/> <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='6094ad8ab496796f35fd8b18068a7cc8'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1288%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='6094ad8ab496796f35fd8b18068a7cc8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1288">Educational Codeforces Round 80 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='6094ad8ab496796f35fd8b18068a7cc8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1288/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Потоки в графах"> потоки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2900 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6094ad8ab496796f35fd8b18068a7cc8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="516092"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6094ad8ab496796f35fd8b18068a7cc8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="516092"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73061" title="73061" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="18394:18395" 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/73105" title="Разбор Educational Codeforces Round 80" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10603:10604" 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/1288">Задачи</a></li> <li><a href="/contest/1288/submit">Отослать</a></li> <li><a href="/contest/1288/my">Мои посылки</a></li> <li><a href="/contest/1288/status">Статус</a></li> <li><a href="/contest/1288/hacks">Взломы</a></li> <li><a href="/contest/1288/standings">Положение</a></li> <li><a href="/contest/1288/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e8db69cd8b1fff1cacce913c7b2404acd0ae2ede"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>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_2$$$ вершин, а также в графе $$$m$$$ ребер. <span class="tex-font-style-bf">Граф может содержать кратные ребра</span>.</p><p>Первоначально, все ребра графа бесцветные. Каждое ребро вы можете либо оставить бесцветным (это бесплатно), либо покрасить в красный (стоимость данного действия $$$r$$$ монет), либо покрасить в синий (за $$$b$$$ монет). Никакое ребро не может быть покрашено в оба цвета одновременно.</p><p>Также в графе вершины разбиваются на три типа — бесцветные, красные и синие. Цветные вершины добавляют дополнительные ограничения на раскраску ребер:</p><ul> <li> у каждой красной вершины количество смежных с ней красных ребер должно быть <span class="tex-font-style-bf">строго больше</span>, чем смежных с ней синих ребер; </li><li> у каждой синей вершины количество смежных с ней синих ребер должно быть <span class="tex-font-style-bf">строго больше</span>, чем смежных с ней красных ребер. </li></ul><p>Бесцветные вершины не накладывают никаких ограничений.</p><p>Ваша задача — раскрасить некоторые (возможно, никакие) ребра так, чтобы выполнялись заданные ограничения, и среди всех возможных раскрасок выбрать такую, суммарная стоимость которой минимальна. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы пять целых чисел $$$n_1$$$, $$$n_2$$$, $$$m$$$, $$$r$$$ и $$$b$$$ ($$$1 \le n_1, n_2, m, r, b \le 200$$$) — количество вершин в первой доле, количество вершин во второй доле, количество ребер, стоимость покраски одного ребра в красный и стоимость покраски в синий соответственно.</p><p>Во второй строке задана одна строка из $$$n_1$$$ символов. Каждый символ — это <span class="tex-font-style-tt">U</span>, <span class="tex-font-style-tt">R</span> или <span class="tex-font-style-tt">B</span>. Если $$$i$$$-й символ — это <span class="tex-font-style-tt">U</span>, то $$$i$$$-я вершина первой доли бесцветная; <span class="tex-font-style-tt">R</span> соответствует красной вершине, а <span class="tex-font-style-tt">B</span> — синей вершине.</p><p>В третьей строке задана строка из $$$n_2$$$ символов. Каждый символ — это также <span class="tex-font-style-tt">U</span>, <span class="tex-font-style-tt">R</span> или <span class="tex-font-style-tt">B</span>. Данная строка задает цвета вершин второй доли аналогичным образом.</p><p>Далее следуют $$$m$$$ строк: в $$$i$$$-й строке заданы два целых числа $$$u_i$$$ и $$$v_i$$$ ($$$1 \le u_i \le n_1$$$, $$$1 \le v_i \le n_2$$$), задающие ребро между вершиной $$$u_i$$$ из первой доли и вершиной $$$v_i$$$ из второй доли.</p><p>Граф может содержать кратные ребра.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если не существует раскраски ребер, которая удовлетворяет всем заданным ограничениям, — выведите $$$-1$$$.</p><p>Иначе, выведите число $$$c$$$, обозначающее минимальную суммарную стоимость раскраски, и строку из $$$m$$$ символов. $$$i$$$-й символ должен быть <span class="tex-font-style-tt">U</span>, если $$$i$$$-е ребро осталось бесцветным, <span class="tex-font-style-tt">R</span>, если $$$i$$$-е ребро покрашено в красный, или <span class="tex-font-style-tt">B</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> 3 2 6 10 15 RRB UB 3 2 2 2 1 2 1 1 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 35 BUURRU </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 3 4 5 RRR B 2 1 1 1 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 3 4 5 URU B 2 1 1 1 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 14 RBB </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:54: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:'8124941f59f016db',t:'MTY5NjY2NTI5Mi44MzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0442\u043e\u043a\u0438 \u0432 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u043e\u0442\u043e\u043a\u0438", "*2900"]
1290A
1290
A
ru
A. Контроль сознания
<div class="problem-statement"><div class="header"><div class="title">A. Контроль сознания</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы и ваш $$$n - 1$$$ друг нашли массив целых чисел $$$a_1, a_2, \dots, a_n$$$. Вы решили разделить его следующим образом: все $$$n$$$ человек встают в линию в определенном порядке. Каждую минуту, человек в начале линии выбирает либо первый, либо последний элемент массива, удаляет его и забирает себе. Затем, он выходит из линии и процесс продолжается со следующим стоящим в линии человеком.</p><p>Вы стоите на $$$m$$$-й позиции в линии. <span class="tex-font-style-bf">Перед тем, как процесс начнется</span>, вы можете выбрать не больше чем $$$k$$$ различных людей в линии и каждого из них убедить всегда брать либо первый, либо последний элемент массива во время их хода (для каждого человека свой выбор, не обязательно у всех одинаковый), не зависимо от того, какие это элементы. <span class="tex-font-style-bf">После того, как процесс начнется, вы не сможете убедить больше людей или изменить выбор уже убежденных вами людей</span>.</p><p>Предположим, что вы сделаете ваш выбор оптимально. Чему равно максимальное целое число $$$x$$$, такое что, вне зависимости от ходов тех друзей, которых вы не выбрали, чтобы убедить, элемент массива, который вы получите на вашем ходу, будет <span class="tex-font-style-bf">не меньше, чем</span> $$$x$$$?</p><p>Обратите внимание, что друзья, которых вы не выбрали для того, чтобы убедить сделать их заранее определенный вами выбор, могут делать свой выбор <span class="tex-font-style-bf"><span class="tex-font-style-underline">произвольно</span></span> и они не обязательно будут брать наибольший доступный для них элемент.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат несколько тестовых случаев. В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 1000$$$)  — количество тестовых случаев. В следующих строках находится их описание.</p><p>В первой строке описания каждого тестового случая находятся три разделенных пробелом целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$1 \le m \le n \le 3500$$$, $$$0 \le k \le n - 1$$$)  — количество элементов в массиве, ваша позиция в линии и количество человек, чей выбор вы можете зафиксировать.</p><p>Во второй строке описания каждого тестового случая содержится $$$n$$$ положительных целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — элементы массива.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем тестовым случаям не превосходит $$$3500$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите наибольшее целое число $$$x$$$, такое что вы можете гарантировать себе получить число не меньше, чем $$$x$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 4 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, одной из оптимальных стратегий является убедить первого человека брать последний элемент и второго человека брать первый элемент.</p><ul> <li> первый человек возьмет последний элемент ($$$5$$$), потому что он или она были убеждены вами взять последний элемент. После этого хода оставшийся массив будет $$$[2, 9, 2, 3, 8]$$$; </li><li> второй человек возьмет первый элемент ($$$2$$$), потому что он или она были убеждены вами взять первый элемент. После этого хода оставшийся массив будет $$$[9, 2, 3, 8]$$$; </li><li> если третий человек выберет взять первый элемент ($$$9$$$), к вашему ходу оставшийся массив будет $$$[2, 3, 8]$$$ и вы сможете взять $$$8$$$ (последний элемент); </li><li> если третий человек выберет взять последний элемент ($$$8$$$), к вашему ходу оставшийся массив будет $$$[9, 2, 3]$$$ и вы сможете взять $$$9$$$ (первый элемент). </li></ul><p>Таким образом, эта стратегия гарантирует получить в конце число не меньше, чем $$$8$$$. Можно доказать, что не существует стратегии, гарантирующей получить число не меньше чем $$$9$$$. Таким образом, ответ равен $$$8$$$.</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="0d75f8aaa5ceb4d475e391e87bddae44"/> <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="08675d1611244d997fc00a21cd5df84da1c60370"/> <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='0d75f8aaa5ceb4d475e391e87bddae44'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1290%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='0d75f8aaa5ceb4d475e391e87bddae44'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1290">Codeforces Round 616 (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='0d75f8aaa5ceb4d475e391e87bddae44'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1290/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='0d75f8aaa5ceb4d475e391e87bddae44'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="529277"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0d75f8aaa5ceb4d475e391e87bddae44'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="529277"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73462" title="Codeforces Round #616" target="_blank">Codeforces Round #616 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10335" resourceName="Codeforces Round #616" resourceManual="true" src="//codeforces.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/73563" title="Codeforces Round #616 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10345" resourceName="Codeforces Round #616 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/1290">Задачи</a></li> <li><a href="/contest/1290/submit">Отослать</a></li> <li><a href="/contest/1290/my">Мои посылки</a></li> <li><a href="/contest/1290/status">Статус</a></li> <li><a href="/contest/1290/hacks">Взломы</a></li> <li><a href="/contest/1290/room/1">Комната</a></li> <li><a href="/contest/1290/standings">Положение</a></li> <li><a href="/contest/1290/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_31aa655d15201fe417dc84ca67377536bc283dc9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Контроль сознания</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы и ваш $$$n - 1$$$ друг нашли массив целых чисел $$$a_1, a_2, \dots, a_n$$$. Вы решили разделить его следующим образом: все $$$n$$$ человек встают в линию в определенном порядке. Каждую минуту, человек в начале линии выбирает либо первый, либо последний элемент массива, удаляет его и забирает себе. Затем, он выходит из линии и процесс продолжается со следующим стоящим в линии человеком.</p><p>Вы стоите на $$$m$$$-й позиции в линии. <span class="tex-font-style-bf">Перед тем, как процесс начнется</span>, вы можете выбрать не больше чем $$$k$$$ различных людей в линии и каждого из них убедить всегда брать либо первый, либо последний элемент массива во время их хода (для каждого человека свой выбор, не обязательно у всех одинаковый), не зависимо от того, какие это элементы. <span class="tex-font-style-bf">После того, как процесс начнется, вы не сможете убедить больше людей или изменить выбор уже убежденных вами людей</span>.</p><p>Предположим, что вы сделаете ваш выбор оптимально. Чему равно максимальное целое число $$$x$$$, такое что, вне зависимости от ходов тех друзей, которых вы не выбрали, чтобы убедить, элемент массива, который вы получите на вашем ходу, будет <span class="tex-font-style-bf">не меньше, чем</span> $$$x$$$?</p><p>Обратите внимание, что друзья, которых вы не выбрали для того, чтобы убедить сделать их заранее определенный вами выбор, могут делать свой выбор <span class="tex-font-style-bf"><span class="tex-font-style-underline">произвольно</span></span> и они не обязательно будут брать наибольший доступный для них элемент.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат несколько тестовых случаев. В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 1000$$$)  — количество тестовых случаев. В следующих строках находится их описание.</p><p>В первой строке описания каждого тестового случая находятся три разделенных пробелом целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$1 \le m \le n \le 3500$$$, $$$0 \le k \le n - 1$$$)  — количество элементов в массиве, ваша позиция в линии и количество человек, чей выбор вы можете зафиксировать.</p><p>Во второй строке описания каждого тестового случая содержится $$$n$$$ положительных целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — элементы массива.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем тестовым случаям не превосходит $$$3500$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите наибольшее целое число $$$x$$$, такое что вы можете гарантировать себе получить число не меньше, чем $$$x$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 4 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, одной из оптимальных стратегий является убедить первого человека брать последний элемент и второго человека брать первый элемент.</p><ul> <li> первый человек возьмет последний элемент ($$$5$$$), потому что он или она были убеждены вами взять последний элемент. После этого хода оставшийся массив будет $$$[2, 9, 2, 3, 8]$$$; </li><li> второй человек возьмет первый элемент ($$$2$$$), потому что он или она были убеждены вами взять первый элемент. После этого хода оставшийся массив будет $$$[9, 2, 3, 8]$$$; </li><li> если третий человек выберет взять первый элемент ($$$9$$$), к вашему ходу оставшийся массив будет $$$[2, 3, 8]$$$ и вы сможете взять $$$8$$$ (последний элемент); </li><li> если третий человек выберет взять последний элемент ($$$8$$$), к вашему ходу оставшийся массив будет $$$[9, 2, 3]$$$ и вы сможете взять $$$9$$$ (первый элемент). </li></ul><p>Таким образом, эта стратегия гарантирует получить в конце число не меньше, чем $$$8$$$. Можно доказать, что не существует стратегии, гарантирующей получить число не меньше чем $$$9$$$. Таким образом, ответ равен $$$8$$$.</p><p>Во втором тестовом случае, одной из оптимальных стратегий является убедить первого человека взять первый элемент. Тогда, в худшем случае второй и третий человек возьмут первый элементы и вы получите число $$$4$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:54: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:'81249427fcac75a3',t:'MTY5NjY2NTI5NC4zMjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1600"]
1290B
1290
B
ru
B. Неприводимые анаграммы
<div class="problem-statement"><div class="header"><div class="title">B. Неприводимые анаграммы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Назовем две строки $$$s$$$ и $$$t$$$ <span class="tex-font-style-it">анаграммами</span> друг друга, если можно так переставить символы в строке $$$s$$$, чтобы получить строку, равную $$$t$$$.</p><p>Рассмотрим две строки $$$s$$$ и $$$t$$$, <span class="tex-font-style-bf">являющиеся анаграммами друг друга</span>. Будем говорить, что $$$t$$$ это <span class="tex-font-style-it">приводимая анаграмма</span> строки $$$s$$$, если существует такое целое число $$$k \ge 2$$$ и $$$2k$$$ непустых строк $$$s_1, t_1, s_2, t_2, \dots, s_k, t_k$$$, которые удовлетворяют следующим условиям:</p><ol> <li> Если мы запишем в линию строки $$$s_1, s_2, \dots, s_k$$$ в таком порядке, то получившаяся строка будет равна $$$s$$$; </li><li> Если мы запишем в линию строки $$$t_1, t_2, \dots, t_k$$$ в таком порядке, то получившаяся строка будет равна $$$t$$$; </li><li> Для всех целых $$$i$$$ между $$$1$$$ и $$$k$$$ включительно, $$$s_i$$$ и $$$t_i$$$ являются анаграммами. </li></ol><p>Если таких строк не существует, тогда $$$t$$$ называется <span class="tex-font-style-it">неприводимой анаграммой</span> строки $$$s$$$. <span class="tex-font-style-bf">Обратите внимание, что этот термин определяется только в случае, когда $$$s$$$ и $$$t$$$ это анаграммы</span>.</p><p>Например, рассмотрим строку $$$s = $$$ «<span class="tex-font-style-tt">gamegame</span>». Тогда строка $$$t = $$$ «<span class="tex-font-style-tt">megamage</span>» это приводимая анаграмма для $$$s$$$, потому что мы можем выбрать, например, $$$s_1 = $$$ «<span class="tex-font-style-tt">game</span>», $$$s_2 = $$$ «<span class="tex-font-style-tt">gam</span>», $$$s_3 = $$$ «<span class="tex-font-style-tt">e</span>» и $$$t_1 = $$$ «<span class="tex-font-style-tt">mega</span>», $$$t_2 = $$$ «<span class="tex-font-style-tt">mag</span>», $$$t_3 = $$$ «<span class="tex-font-style-tt">e</span>»:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/62af0aaee3571a1f20e5fd483333e25ef163e0c2.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>С другой стороны, можно показать, что $$$t = $$$ «<span class="tex-font-style-tt">memegaga</span>» это неприводимая анаграмма для $$$s$$$.</p><p>Вам будет дана строка $$$s$$$ и $$$q$$$ запросов, каждый представляется двумя целыми числами $$$1 \le l \le r \le |s|$$$ (где за $$$|s|$$$ обозначается длина строки $$$s$$$). Для каждого запроса, вы должны определить, имеет ли подстрока строки $$$s$$$, с $$$l$$$-о по $$$r$$$-й символ, включительно, <span class="tex-font-style-underline"> хотя бы одну</span> неприводимую анаграмму.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится строка $$$s$$$, состоящая из строчных символов латинского алфавита ($$$1 \le |s| \le 2 \cdot 10^5$$$).</p><p>Во второй строке содержится единственное целое число $$$q$$$ ($$$1 \le q \le 10^5$$$)  — количество запросов.</p><p>Следующие $$$q$$$ строк содержат по два целых числа $$$l$$$ и $$$r$$$ ($$$1 \le l \le r \le |s|$$$), обозначающие очередной запрос для подстроки $$$s$$$, состоящей из символов с $$$l$$$-о по $$$r$$$-й.</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> aaaaa 3 1 1 2 4 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No Yes </pre></div><div class="input"><div class="title">Входные данные</div><pre> aabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No Yes Yes Yes No No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, в первом и третьем запросах, подстрока будет «<span class="tex-font-style-tt">a</span>» и она имеет саму себя как неприводимую анаграмму, так как две и больше непустые строки, записанные вместе, не смогут дать строку «<span class="tex-font-style-tt">a</span>». С другой стороны, во втором запросе, подстрока будет «<span class="tex-font-style-tt">aaa</span>», которая не имеет неприводимых анаграмм: ее единственная анаграмма это она сама и мы можем выбрать $$$s_1 = $$$ «<span class="tex-font-style-tt">a</span>», $$$s_2 = $$$ «<span class="tex-font-style-tt">aa</span>», $$$t_1 = $$$ «<span class="tex-font-style-tt">a</span>», $$$t_2 = $$$ «<span class="tex-font-style-tt">aa</span>», чтобы показать, что это приводимая анаграмма.</p><p>Во втором запросе второго тестового случая, подстрока будет «<span class="tex-font-style-tt">abb</span>» и она имеет, например, неприводимую анаграмму «<span class="tex-font-style-tt">bba</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="f08a4237e8b7aa2d9551317101bd3083"/> <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="08675d1611244d997fc00a21cd5df84da1c60370"/> <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='f08a4237e8b7aa2d9551317101bd3083'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1290%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='f08a4237e8b7aa2d9551317101bd3083'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1290">Codeforces Round 616 (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='f08a4237e8b7aa2d9551317101bd3083'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1290/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *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='f08a4237e8b7aa2d9551317101bd3083'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="529278"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f08a4237e8b7aa2d9551317101bd3083'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="529278"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73462" title="Codeforces Round #616" target="_blank">Codeforces Round #616 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10335" resourceName="Codeforces Round #616" resourceManual="true" src="//codeforces.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/73563" title="Codeforces Round #616 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10345" resourceName="Codeforces Round #616 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/1290">Задачи</a></li> <li><a href="/contest/1290/submit">Отослать</a></li> <li><a href="/contest/1290/my">Мои посылки</a></li> <li><a href="/contest/1290/status">Статус</a></li> <li><a href="/contest/1290/hacks">Взломы</a></li> <li><a href="/contest/1290/room/1">Комната</a></li> <li><a href="/contest/1290/standings">Положение</a></li> <li><a href="/contest/1290/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a79c2d01b1dc5d4790c7225cfca69ad0b38511cc"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Неприводимые анаграммы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Назовем две строки $$$s$$$ и $$$t$$$ <span class="tex-font-style-it">анаграммами</span> друг друга, если можно так переставить символы в строке $$$s$$$, чтобы получить строку, равную $$$t$$$.</p><p>Рассмотрим две строки $$$s$$$ и $$$t$$$, <span class="tex-font-style-bf">являющиеся анаграммами друг друга</span>. Будем говорить, что $$$t$$$ это <span class="tex-font-style-it">приводимая анаграмма</span> строки $$$s$$$, если существует такое целое число $$$k \ge 2$$$ и $$$2k$$$ непустых строк $$$s_1, t_1, s_2, t_2, \dots, s_k, t_k$$$, которые удовлетворяют следующим условиям:</p><ol> <li> Если мы запишем в линию строки $$$s_1, s_2, \dots, s_k$$$ в таком порядке, то получившаяся строка будет равна $$$s$$$; </li><li> Если мы запишем в линию строки $$$t_1, t_2, \dots, t_k$$$ в таком порядке, то получившаяся строка будет равна $$$t$$$; </li><li> Для всех целых $$$i$$$ между $$$1$$$ и $$$k$$$ включительно, $$$s_i$$$ и $$$t_i$$$ являются анаграммами. </li></ol><p>Если таких строк не существует, тогда $$$t$$$ называется <span class="tex-font-style-it">неприводимой анаграммой</span> строки $$$s$$$. <span class="tex-font-style-bf">Обратите внимание, что этот термин определяется только в случае, когда $$$s$$$ и $$$t$$$ это анаграммы</span>.</p><p>Например, рассмотрим строку $$$s = $$$ «<span class="tex-font-style-tt">gamegame</span>». Тогда строка $$$t = $$$ «<span class="tex-font-style-tt">megamage</span>» это приводимая анаграмма для $$$s$$$, потому что мы можем выбрать, например, $$$s_1 = $$$ «<span class="tex-font-style-tt">game</span>», $$$s_2 = $$$ «<span class="tex-font-style-tt">gam</span>», $$$s_3 = $$$ «<span class="tex-font-style-tt">e</span>» и $$$t_1 = $$$ «<span class="tex-font-style-tt">mega</span>», $$$t_2 = $$$ «<span class="tex-font-style-tt">mag</span>», $$$t_3 = $$$ «<span class="tex-font-style-tt">e</span>»:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/62af0aaee3571a1f20e5fd483333e25ef163e0c2.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>С другой стороны, можно показать, что $$$t = $$$ «<span class="tex-font-style-tt">memegaga</span>» это неприводимая анаграмма для $$$s$$$.</p><p>Вам будет дана строка $$$s$$$ и $$$q$$$ запросов, каждый представляется двумя целыми числами $$$1 \le l \le r \le |s|$$$ (где за $$$|s|$$$ обозначается длина строки $$$s$$$). Для каждого запроса, вы должны определить, имеет ли подстрока строки $$$s$$$, с $$$l$$$-о по $$$r$$$-й символ, включительно, <span class="tex-font-style-underline"> хотя бы одну</span> неприводимую анаграмму.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится строка $$$s$$$, состоящая из строчных символов латинского алфавита ($$$1 \le |s| \le 2 \cdot 10^5$$$).</p><p>Во второй строке содержится единственное целое число $$$q$$$ ($$$1 \le q \le 10^5$$$)  — количество запросов.</p><p>Следующие $$$q$$$ строк содержат по два целых числа $$$l$$$ и $$$r$$$ ($$$1 \le l \le r \le |s|$$$), обозначающие очередной запрос для подстроки $$$s$$$, состоящей из символов с $$$l$$$-о по $$$r$$$-й.</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> aaaaa 3 1 1 2 4 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No Yes </pre></div><div class="input"><div class="title">Входные данные</div><pre> aabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No Yes Yes Yes No No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, в первом и третьем запросах, подстрока будет «<span class="tex-font-style-tt">a</span>» и она имеет саму себя как неприводимую анаграмму, так как две и больше непустые строки, записанные вместе, не смогут дать строку «<span class="tex-font-style-tt">a</span>». С другой стороны, во втором запросе, подстрока будет «<span class="tex-font-style-tt">aaa</span>», которая не имеет неприводимых анаграмм: ее единственная анаграмма это она сама и мы можем выбрать $$$s_1 = $$$ «<span class="tex-font-style-tt">a</span>», $$$s_2 = $$$ «<span class="tex-font-style-tt">aa</span>», $$$t_1 = $$$ «<span class="tex-font-style-tt">a</span>», $$$t_2 = $$$ «<span class="tex-font-style-tt">aa</span>», чтобы показать, что это приводимая анаграмма.</p><p>Во втором запросе второго тестового случая, подстрока будет «<span class="tex-font-style-tt">abb</span>» и она имеет, например, неприводимую анаграмму «<span class="tex-font-style-tt">bba</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:54: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:'812494320a0078ff',t:'MTY5NjY2NTI5NS43NzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\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.", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u0442\u0440\u043e\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1800"]
1290C
1290
C
ru
C. Освещение префиксов
<div class="problem-statement"><div class="header"><div class="title">C. Освещение префиксов</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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$$$. Каждая лампа изначально либо выключена ($$$0$$$) или включена ($$$1$$$).</p><p>Вам дано $$$k$$$ подмножеств $$$A_1, \ldots, A_k$$$ множества ламп $$$\{1, 2, \dots, n\}$$$, таких что пересечение любых трех подмножеств пусто. Другими словами, для всех $$$1 \le i_1 &lt; i_2 &lt; i_3 \le k$$$ выполнено $$$A_{i_1} \cap A_{i_2} \cap A_{i_3} = \varnothing$$$.</p><p>За одну операцию вы можете выбрать одно из этих $$$k$$$ подмножеств и изменить состояние всех ламп из этого подмножества (выключенные лампы становятся включенными, включенные становятся выключенными). Гарантируется, что для данных подмножеств можно совершить несколько операций так, чтобы все лампы стали включенными.</p><p>Обозначим за $$$m_i$$$ минимальное количество операций, которое вы должны совершить, чтобы первые $$$i$$$ ламп оказались включенными. Обратите внимание, что при этом состояние других ламп (с номерами между $$$i+1$$$ и $$$n$$$) может быть любым.</p><p>Посчитайте $$$m_i$$$ для всех $$$1 \le i \le n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 3 \cdot 10^5$$$).</p><p>Во второй строке находится двоичная строка длины $$$n$$$, обозначающая начальное состояние каждой лампы (лампа $$$i$$$ выключена, если $$$s_i = 0$$$, включена, если $$$s_i = 1$$$).</p><p>Описание каждого из $$$k$$$ подмножеств следует, в следующем формате:</p><p>В первой строке описания находится единственное целое число $$$c$$$ ($$$1 \le c \le n$$$)  — количество элементов в подмножестве.</p><p>Во второй строке описания находится $$$c$$$ различных целых чисел $$$x_1, \ldots, x_c$$$ ($$$1 \le x_i \le n$$$)  — элементы подмножества.</p><p>Гарантируется, что:</p><ul> <li> Пересечение любых трех подмножеств пусто; </li><li> С помощью нескольких операций можно сделать все лампы одновременно включенными. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести $$$n$$$ строк. В $$$i$$$-й строке должно содержаться единственное целое число $$$m_i$$$  — минимальное количество операций, необходимое для того чтобы сделать все лампы с номерами от $$$1$$$ до $$$i$$$ включенными. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 3 3 3 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 1 4 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 00011 3 1 2 3 1 4 3 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте: </p><ul> <li> Для $$$i = 1$$$, мы можем сделать одну операцию с множеством $$$A_1$$$, итоговые состояния будут $$$1010110$$$; </li><li> Для $$$i = 2$$$, мы можем сделать операции с множествами $$$A_1$$$ и $$$A_3$$$, итоговые состояния будут $$$1100110$$$; </li><li> For $$$i \ge 3$$$, we can apply operations on $$$A_1$$$, $$$A_2$$$ and $$$A_3$$$, the final states will be $$$1111111$$$. </li></ul><p>Во втором тесте: </p><ul> <li> Для $$$i \le 6$$$, мы можем просто сделать одну операцию с множеством $$$A_2$$$, итоговые состояния будут $$$11111101$$$; </li><li> Для $$$i \ge 7$$$, мы можем сделать операции с множествами $$$A_1, A_3, A_4, A_6$$$, итоговые состояния будут $$$11111111$$$. </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="969940e34121ad75e38a294b6640f4f0"/> <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="08675d1611244d997fc00a21cd5df84da1c60370"/> <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='969940e34121ad75e38a294b6640f4f0'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1290%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='969940e34121ad75e38a294b6640f4f0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1290">Codeforces Round 616 (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='969940e34121ad75e38a294b6640f4f0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1290/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств"> снм </span> </div> <div class="roundbox borderTopRound 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='969940e34121ad75e38a294b6640f4f0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="529279"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='969940e34121ad75e38a294b6640f4f0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="529279"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73462" title="Codeforces Round #616" target="_blank">Codeforces Round #616 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10335" resourceName="Codeforces Round #616" resourceManual="true" src="//codeforces.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/73563" title="Codeforces Round #616 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10345" resourceName="Codeforces Round #616 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/1290">Задачи</a></li> <li><a href="/contest/1290/submit">Отослать</a></li> <li><a href="/contest/1290/my">Мои посылки</a></li> <li><a href="/contest/1290/status">Статус</a></li> <li><a href="/contest/1290/hacks">Взломы</a></li> <li><a href="/contest/1290/room/1">Комната</a></li> <li><a href="/contest/1290/standings">Положение</a></li> <li><a href="/contest/1290/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_69f6408bb54093db7a4d7953b1ad127b491fe6da"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>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$$$ ламп, пронумерованных целыми числами от $$$1$$$ до $$$n$$$. Каждая лампа изначально либо выключена ($$$0$$$) или включена ($$$1$$$).</p><p>Вам дано $$$k$$$ подмножеств $$$A_1, \ldots, A_k$$$ множества ламп $$$\{1, 2, \dots, n\}$$$, таких что пересечение любых трех подмножеств пусто. Другими словами, для всех $$$1 \le i_1 &lt; i_2 &lt; i_3 \le k$$$ выполнено $$$A_{i_1} \cap A_{i_2} \cap A_{i_3} = \varnothing$$$.</p><p>За одну операцию вы можете выбрать одно из этих $$$k$$$ подмножеств и изменить состояние всех ламп из этого подмножества (выключенные лампы становятся включенными, включенные становятся выключенными). Гарантируется, что для данных подмножеств можно совершить несколько операций так, чтобы все лампы стали включенными.</p><p>Обозначим за $$$m_i$$$ минимальное количество операций, которое вы должны совершить, чтобы первые $$$i$$$ ламп оказались включенными. Обратите внимание, что при этом состояние других ламп (с номерами между $$$i+1$$$ и $$$n$$$) может быть любым.</p><p>Посчитайте $$$m_i$$$ для всех $$$1 \le i \le n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 3 \cdot 10^5$$$).</p><p>Во второй строке находится двоичная строка длины $$$n$$$, обозначающая начальное состояние каждой лампы (лампа $$$i$$$ выключена, если $$$s_i = 0$$$, включена, если $$$s_i = 1$$$).</p><p>Описание каждого из $$$k$$$ подмножеств следует, в следующем формате:</p><p>В первой строке описания находится единственное целое число $$$c$$$ ($$$1 \le c \le n$$$)  — количество элементов в подмножестве.</p><p>Во второй строке описания находится $$$c$$$ различных целых чисел $$$x_1, \ldots, x_c$$$ ($$$1 \le x_i \le n$$$)  — элементы подмножества.</p><p>Гарантируется, что:</p><ul> <li> Пересечение любых трех подмножеств пусто; </li><li> С помощью нескольких операций можно сделать все лампы одновременно включенными. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести $$$n$$$ строк. В $$$i$$$-й строке должно содержаться единственное целое число $$$m_i$$$  — минимальное количество операций, необходимое для того чтобы сделать все лампы с номерами от $$$1$$$ до $$$i$$$ включенными. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 3 3 3 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 1 4 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 00011 3 1 2 3 1 4 3 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте: </p><ul> <li> Для $$$i = 1$$$, мы можем сделать одну операцию с множеством $$$A_1$$$, итоговые состояния будут $$$1010110$$$; </li><li> Для $$$i = 2$$$, мы можем сделать операции с множествами $$$A_1$$$ и $$$A_3$$$, итоговые состояния будут $$$1100110$$$; </li><li> For $$$i \ge 3$$$, we can apply operations on $$$A_1$$$, $$$A_2$$$ and $$$A_3$$$, the final states will be $$$1111111$$$. </li></ul><p>Во втором тесте: </p><ul> <li> Для $$$i \le 6$$$, мы можем просто сделать одну операцию с множеством $$$A_2$$$, итоговые состояния будут $$$11111101$$$; </li><li> Для $$$i \ge 7$$$, мы можем сделать операции с множествами $$$A_1, A_3, A_4, A_6$$$, итоговые состояния будут $$$11111111$$$. </li></ul></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:54: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:'8124943a2ca31628',t:'MTY5NjY2NTI5Ny4xMjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u043d\u043c", "*2400"]
1290D
1290
D
ru
D. Сорта кофе (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">D. Сорта кофе (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это сложная версия этой задачи. Вы можете найти простую версию в Div. 2 контесте. Обе версии отличаются только в ограничении на количество раз, которое вы можете попросить вашего друга попробовать кофе.</span></p><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Вы собираетесь поехать в другой город, где живет один из ваших друзей. В этом городе $$$n$$$ кафе, где число $$$n$$$ является степенью двойки. В $$$i$$$-м кафе варят кофе сорта $$$a_i$$$.</p><p>Поскольку вы большой любитель кофе, перед тем, как выбрать поехать ли в этот город или нет, <span class="tex-font-style-bf">вы хотите узнать количество различных сортов кофе $$$d$$$</span>, которое варят в этом городе.</p><p>Вы не знаете значений $$$a_1, \ldots, a_n$$$. К счастью, ваш друг хорошо запоминает события последних $$$k$$$ дней, где $$$k$$$ это степень двойки.</p><p>Каждый день, вы можете попросить его попробовать чашечку кофе, сваренного в кафе с номером $$$c$$$ и он скажет, пробовал ли он кофе того же сорта в последние $$$k$$$ дней.</p><p>Также вы можете попросить его забыть все, что он пробовал до этого. После этого он забудет все предыдущие разы, когда он пробовал кофе. Вы можете делать это не больше $$$30\ 000$$$ раз.</p><p>Более формально, память вашего друга это некоторая очередь $$$S$$$. Сделать запрос сходить попробовать кофе в кафе с номером $$$c$$$ означает: </p><ul> <li> Сказать вам, есть ли $$$a_c$$$ в $$$S$$$; </li><li> Добавить $$$a_c$$$ в конец очереди $$$S$$$; </li><li> Если $$$|S| &gt; k$$$, удалить первый элемент очереди $$$S$$$. </li></ul><p>Запрос забывания всех посещений кафе удаляет все элементы очереди $$$S$$$, то есть отчищает ее.</p><p>Вы можете попросить вашего друга попробовать не больше $$$\dfrac{3n^2}{2k}$$$ чашек кофе. Найдите разнообразность города $$$d$$$ (количество различных значений в массиве $$$a$$$).</p><p>Обратите внимание, что попросить вашего друга забыть все походы в кафе, что были до этого <span class="tex-font-style-bf">не считается</span> среди количества запросов попросить вашего друга попробовать кофе.</p><p>В некоторых тестах поведение интерактора будет <span class="tex-font-style-bf">адаптивным</span>. Это означает, что массив $$$a$$$ может быть <span class="tex-font-style-bf">не фиксированным</span> до начала тестирования вашей программы и <span class="tex-font-style-bf">может зависеть от ваших запросов</span>. Гарантируется, что в любой момент тестирования, существует хотя бы один массив $$$a$$$, для которого верны все данные до этого ответы на запросы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 1024$$$, $$$k$$$ и $$$n$$$ это степени двойки).</p><p>Гарантируется, что $$$\dfrac{3n^2}{2k} \le 15\ 000$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Вы начинаете взаимодействие со считывания двух чисел $$$n$$$ и $$$k$$$.</p><ul><li> Для того, чтобы попросить вашего друга попробовать чашечку кофе в кафе с номером $$$c$$$, в отдельной строке выведите<p><span class="tex-font-style-tt">? $$$c$$$</span></p><p>Тут $$$c$$$ должно удовлетворять условиям $$$1 \le c \le n$$$. Не забывайте сделать сброс буфера потока вывода после этого.</p><p>В ответ вы получите символ <span class="tex-font-style-tt">Y</span> (да) или <span class="tex-font-style-tt">N</span> (нет), сообщающий вам, встречался ли сорт кофе $$$a_c$$$ среди последних $$$k$$$ сортов кофе в памяти вашего друга.</p></li><li> Для того чтобы отчистить память вашего друга, в отдельной строке выведите единственный символ <span class="tex-font-style-tt">R</span> (<span class="tex-font-style-bf">большая латинская буква</span>). Вы можете сделать этот запрос не более $$$30\ 000$$$ раз.</li><li> После того, как вы определили количество $$$d$$$ различных сортов кофе, выведите<p><span class="tex-font-style-tt">! $$$d$$$</span></p></li></ul><p>В случае, если запрос, сделанный вами, некорректный или вы сделали больше, чем $$$\frac{3n^2}{2k}$$$ запросов типа <span class="tex-font-style-tt">?</span> или больше, чем $$$30\ 000$$$ запросов типа <span class="tex-font-style-tt">R</span>, в ответ тестирующая программа выведет символ <span class="tex-font-style-tt">E</span> и закончит тестирование. Вы получите вердикт <span class="tex-font-style-bf">Wrong Answer</span>. Будьте осторожны, для этого ваша программа должна немедленно завершиться в этом случае, иначе вердикт посылки может быть любым.</p><p>После вывода запроса не забывайте переводить строку и делать сброс буфера потока вывода. Иначе, вы получите вердикт <span class="tex-font-style-bf">Idleness limit exceeded</span>. Для того, чтобы сделать сброс буфера потока вывода, используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> обратитесь к документации для остальных языков. </li></ul><p><span class="tex-font-style-bf">Взломы</span></p><p>В первой строке теста должно находиться слово <span class="tex-font-style-tt">fixed</span></p><p>Во второй строке должны содержаться два целых числа $$$n$$$ и $$$k$$$, разделенных пробелом ($$$1 \le k \le n \le 1024$$$, $$$k$$$ и $$$n$$$ это степени двойки).</p><p>Должно быть выполнено, что $$$\dfrac{3n^2}{2k} \le 15\ 000$$$.</p><p>В третьей строке должны содержаться $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$, разделенных пробелом ($$$1 \le a_i \le 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 2 N N Y N N N N </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 ? 2 ? 3 ? 4 R ? 4 ? 1 ? 2 ! 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 8 N N N N Y Y </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 2 ? 6 ? 4 ? 5 ? 2 ? 5 ! 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, массив $$$a = [1, 4, 1, 3]$$$. В городе производится $$$3$$$ различных сорта кофе ($$$1$$$, $$$3$$$ и $$$4$$$).</p><p>Последовательные сорта кофе, попробованные вашим другом это $$$1, 4, \textbf{1}, 3, 3, 1, 4$$$ (жирным выделены запросы с ответом <span class="tex-font-style-tt">Y</span>). Обратите внимание, что между двумя запросами <span class="tex-font-style-tt">? 4</span>, был запрос отчищения памяти, поэтому ответ на второй запрос <span class="tex-font-style-tt">? 4</span> был <span class="tex-font-style-tt">N</span>. Если бы этого запроса не было, то ответ на второй запрос <span class="tex-font-style-tt">? 4</span> был бы <span class="tex-font-style-tt">Y</span>.</p><p>Во втором тесте, массив $$$a = [1, 2, 3, 4, 5, 6, 6, 6]$$$. В городе производится $$$6$$$ различных сортов кофе.</p><p>Последовательные сорта кофе, попробованные вашим другом это $$$2, 6, 4, 5, \textbf{2}, \textbf{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="a32e3de10f5a5375e5e606a1160d35f0"/> <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="08675d1611244d997fc00a21cd5df84da1c60370"/> <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='a32e3de10f5a5375e5e606a1160d35f0'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1290%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='a32e3de10f5a5375e5e606a1160d35f0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1290">Codeforces Round 616 (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='a32e3de10f5a5375e5e606a1160d35f0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1290/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='a32e3de10f5a5375e5e606a1160d35f0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="529280"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a32e3de10f5a5375e5e606a1160d35f0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="529280"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73462" title="Codeforces Round #616" target="_blank">Codeforces Round #616 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10335" resourceName="Codeforces Round #616" resourceManual="true" src="//codeforces.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/73563" title="Codeforces Round #616 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10345" resourceName="Codeforces Round #616 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/1290">Задачи</a></li> <li><a href="/contest/1290/submit">Отослать</a></li> <li><a href="/contest/1290/my">Мои посылки</a></li> <li><a href="/contest/1290/status">Статус</a></li> <li><a href="/contest/1290/hacks">Взломы</a></li> <li><a href="/contest/1290/room/1">Комната</a></li> <li><a href="/contest/1290/standings">Положение</a></li> <li><a href="/contest/1290/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b884649a03dc1acf350755e46208a9440a25ef09"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Сорта кофе (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это сложная версия этой задачи. Вы можете найти простую версию в Div. 2 контесте. Обе версии отличаются только в ограничении на количество раз, которое вы можете попросить вашего друга попробовать кофе.</span></p><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Вы собираетесь поехать в другой город, где живет один из ваших друзей. В этом городе $$$n$$$ кафе, где число $$$n$$$ является степенью двойки. В $$$i$$$-м кафе варят кофе сорта $$$a_i$$$.</p><p>Поскольку вы большой любитель кофе, перед тем, как выбрать поехать ли в этот город или нет, <span class="tex-font-style-bf">вы хотите узнать количество различных сортов кофе $$$d$$$</span>, которое варят в этом городе.</p><p>Вы не знаете значений $$$a_1, \ldots, a_n$$$. К счастью, ваш друг хорошо запоминает события последних $$$k$$$ дней, где $$$k$$$ это степень двойки.</p><p>Каждый день, вы можете попросить его попробовать чашечку кофе, сваренного в кафе с номером $$$c$$$ и он скажет, пробовал ли он кофе того же сорта в последние $$$k$$$ дней.</p><p>Также вы можете попросить его забыть все, что он пробовал до этого. После этого он забудет все предыдущие разы, когда он пробовал кофе. Вы можете делать это не больше $$$30\ 000$$$ раз.</p><p>Более формально, память вашего друга это некоторая очередь $$$S$$$. Сделать запрос сходить попробовать кофе в кафе с номером $$$c$$$ означает: </p><ul> <li> Сказать вам, есть ли $$$a_c$$$ в $$$S$$$; </li><li> Добавить $$$a_c$$$ в конец очереди $$$S$$$; </li><li> Если $$$|S| &gt; k$$$, удалить первый элемент очереди $$$S$$$. </li></ul><p>Запрос забывания всех посещений кафе удаляет все элементы очереди $$$S$$$, то есть отчищает ее.</p><p>Вы можете попросить вашего друга попробовать не больше $$$\dfrac{3n^2}{2k}$$$ чашек кофе. Найдите разнообразность города $$$d$$$ (количество различных значений в массиве $$$a$$$).</p><p>Обратите внимание, что попросить вашего друга забыть все походы в кафе, что были до этого <span class="tex-font-style-bf">не считается</span> среди количества запросов попросить вашего друга попробовать кофе.</p><p>В некоторых тестах поведение интерактора будет <span class="tex-font-style-bf">адаптивным</span>. Это означает, что массив $$$a$$$ может быть <span class="tex-font-style-bf">не фиксированным</span> до начала тестирования вашей программы и <span class="tex-font-style-bf">может зависеть от ваших запросов</span>. Гарантируется, что в любой момент тестирования, существует хотя бы один массив $$$a$$$, для которого верны все данные до этого ответы на запросы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 1024$$$, $$$k$$$ и $$$n$$$ это степени двойки).</p><p>Гарантируется, что $$$\dfrac{3n^2}{2k} \le 15\ 000$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Вы начинаете взаимодействие со считывания двух чисел $$$n$$$ и $$$k$$$.</p><ul><li> Для того, чтобы попросить вашего друга попробовать чашечку кофе в кафе с номером $$$c$$$, в отдельной строке выведите<p><span class="tex-font-style-tt">? $$$c$$$</span></p><p>Тут $$$c$$$ должно удовлетворять условиям $$$1 \le c \le n$$$. Не забывайте сделать сброс буфера потока вывода после этого.</p><p>В ответ вы получите символ <span class="tex-font-style-tt">Y</span> (да) или <span class="tex-font-style-tt">N</span> (нет), сообщающий вам, встречался ли сорт кофе $$$a_c$$$ среди последних $$$k$$$ сортов кофе в памяти вашего друга.</p></li><li> Для того чтобы отчистить память вашего друга, в отдельной строке выведите единственный символ <span class="tex-font-style-tt">R</span> (<span class="tex-font-style-bf">большая латинская буква</span>). Вы можете сделать этот запрос не более $$$30\ 000$$$ раз.</li><li> После того, как вы определили количество $$$d$$$ различных сортов кофе, выведите<p><span class="tex-font-style-tt">! $$$d$$$</span></p></li></ul><p>В случае, если запрос, сделанный вами, некорректный или вы сделали больше, чем $$$\frac{3n^2}{2k}$$$ запросов типа <span class="tex-font-style-tt">?</span> или больше, чем $$$30\ 000$$$ запросов типа <span class="tex-font-style-tt">R</span>, в ответ тестирующая программа выведет символ <span class="tex-font-style-tt">E</span> и закончит тестирование. Вы получите вердикт <span class="tex-font-style-bf">Wrong Answer</span>. Будьте осторожны, для этого ваша программа должна немедленно завершиться в этом случае, иначе вердикт посылки может быть любым.</p><p>После вывода запроса не забывайте переводить строку и делать сброс буфера потока вывода. Иначе, вы получите вердикт <span class="tex-font-style-bf">Idleness limit exceeded</span>. Для того, чтобы сделать сброс буфера потока вывода, используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> обратитесь к документации для остальных языков. </li></ul><p><span class="tex-font-style-bf">Взломы</span></p><p>В первой строке теста должно находиться слово <span class="tex-font-style-tt">fixed</span></p><p>Во второй строке должны содержаться два целых числа $$$n$$$ и $$$k$$$, разделенных пробелом ($$$1 \le k \le n \le 1024$$$, $$$k$$$ и $$$n$$$ это степени двойки).</p><p>Должно быть выполнено, что $$$\dfrac{3n^2}{2k} \le 15\ 000$$$.</p><p>В третьей строке должны содержаться $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$, разделенных пробелом ($$$1 \le a_i \le 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 2 N N Y N N N N </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 ? 2 ? 3 ? 4 R ? 4 ? 1 ? 2 ! 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 8 N N N N Y Y </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 2 ? 6 ? 4 ? 5 ? 2 ? 5 ! 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, массив $$$a = [1, 4, 1, 3]$$$. В городе производится $$$3$$$ различных сорта кофе ($$$1$$$, $$$3$$$ и $$$4$$$).</p><p>Последовательные сорта кофе, попробованные вашим другом это $$$1, 4, \textbf{1}, 3, 3, 1, 4$$$ (жирным выделены запросы с ответом <span class="tex-font-style-tt">Y</span>). Обратите внимание, что между двумя запросами <span class="tex-font-style-tt">? 4</span>, был запрос отчищения памяти, поэтому ответ на второй запрос <span class="tex-font-style-tt">? 4</span> был <span class="tex-font-style-tt">N</span>. Если бы этого запроса не было, то ответ на второй запрос <span class="tex-font-style-tt">? 4</span> был бы <span class="tex-font-style-tt">Y</span>.</p><p>Во втором тесте, массив $$$a = [1, 2, 3, 4, 5, 6, 6, 6]$$$. В городе производится $$$6$$$ различных сортов кофе.</p><p>Последовательные сорта кофе, попробованные вашим другом это $$$2, 6, 4, 5, \textbf{2}, \textbf{5}$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:54: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:'81249442ae1600b8',t:'MTY5NjY2NTI5OC41NjQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*3000"]
1290E
1290
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>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Ильдар учитель алгоритмов у Вильяма и Харриса. Сегодня, Ильдар рассказывает Декартово дерево. К сожалению, Харрис заболел, поэтому Ильдар учит сегодня только Вильяма.</p><p>Декартово дерево это корневое дерево, которое может быть построено с помощью последовательности различных целых чисел. Мы строим декартово дерево следующим образом:</p><ol><li> Если последовательность пустая, верните пустое дерево;</li><li> Пусть позиция <span class="tex-font-style-bf">максимального</span> элемента это $$$x$$$;</li><li> Удалите элемент на позиции $$$x$$$ из последовательности и разбейте ее на левую и правую часть от этого элемента (которые могут оказаться пустыми) (элемент на самом деле нужно не удалить навсегда, а временно забрать из последовательности);</li><li> Постройте декартово дерево для каждой части;</li><li> Сделайте новую вершину для элемента, который был на позиции $$$x$$$, который станет корнем всего дерева. Теперь, если корни декартовых деревьев для левой и правой части существовали, они становятся сыновьями для этой вершины;</li><li> Верните полученное дерево.</li></ol><p>Например, это декартово дерево для последовательности $$$4, 2, 7, 3, 5, 6, 1$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f877ecaa038b10e98f7ec812c49db83101751df2.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>После того, как Ильдар рассказал про декартово дерево, он задал домашнее задание. Он начинает с пустой последовательности $$$a$$$.</p><p>В $$$i$$$-м раунде, он добавляет число $$$i$$$ куда-то в $$$a$$$. Затем, он задает вопрос: чему равна сумма размеров поддеревьев для всех вершин в декартовом дереве текущей последовательности $$$a$$$?</p><p>Вершина $$$v$$$ находится в поддереве вершины $$$u$$$, тогда и только тогда, когда $$$v = u$$$ или $$$v$$$ находится в одном из поддеревьев одного из сыновей вершины $$$u$$$. Размер поддерева вершины $$$u$$$ равен количеству вершин $$$v$$$, таких что $$$v$$$ находится в поддереве вершины $$$u$$$.</p><p>Всего Ильдар проведет $$$n$$$ раундов. В качестве домашней работы он просит дать ответ на эти $$$n$$$ вопросов.</p><p>На следующий день, Ильдар сказал Харрису, что он тоже должен выполнить это домашнее задание. Харрис получил финальное состояние последовательности $$$a$$$ от Вильяма. К сожалению, у него нету идей как получить ответы на эти $$$n$$$ вопросов. Помогите Харрису!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$1 \le n \le 150000$$$).</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$). Гарантируется, что каждое целое число от $$$1$$$ до $$$n$$$ встречается в последовательности ровно один раз.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ строк, $$$i$$$-я строка должна содержать единственное целое число  — ответ на $$$i$$$-й вопрос.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 2 4 1 5 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 6 8 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 2 4 5 6 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 6 8 12 17 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>После первого раунда, последовательность это $$$1$$$. Дерево выглядит так:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1294322241a0a31b70bd01f0ecdf83a60ca83ff4.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Ответ равен $$$1$$$.</p><p>После второго раунда, последовательность это $$$2, 1$$$. Дерево выглядит так:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f85f7d3bf9bba20cffc31bfa7a60c0b9b6551b47.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Ответ равен $$$2+1=3$$$.</p><p>После третьего раунда, последовательность это $$$2, 1, 3$$$. Дерево выглядит так:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/380e5934e3aa08e48ff7aac9794081eff1d9780c.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Ответ равен $$$2+1+3=6$$$.</p><p>После четвертого раунда, последовательность это $$$2, 4, 1, 3$$$. Дерево выглядит так:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/cea423eb4d2aab92cb47bddcd5e9fd0390f0bb59.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Ответ равен $$$1+4+1+2=8$$$.</p><p>После пятого раунда, последовательность это $$$2, 4, 1, 5, 3$$$. Дерево выглядит так:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/05b17e05157251662473893bd80e02e4bdaf1869.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Ответ равен $$$1+3+1+5+1=11$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b9c1310b1c2397003c4045a0c1704dcb"/> <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="08675d1611244d997fc00a21cd5df84da1c60370"/> <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='b9c1310b1c2397003c4045a0c1704dcb'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1290%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='b9c1310b1c2397003c4045a0c1704dcb'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1290">Codeforces Round 616 (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='b9c1310b1c2397003c4045a0c1704dcb'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1290/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='b9c1310b1c2397003c4045a0c1704dcb'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="529281"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b9c1310b1c2397003c4045a0c1704dcb'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="529281"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73462" title="Codeforces Round #616" target="_blank">Codeforces Round #616 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10335" resourceName="Codeforces Round #616" resourceManual="true" src="//codeforces.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/73563" title="Codeforces Round #616 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10345" resourceName="Codeforces Round #616 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/1290">Задачи</a></li> <li><a href="/contest/1290/submit">Отослать</a></li> <li><a href="/contest/1290/my">Мои посылки</a></li> <li><a href="/contest/1290/status">Статус</a></li> <li><a href="/contest/1290/hacks">Взломы</a></li> <li><a href="/contest/1290/room/1">Комната</a></li> <li><a href="/contest/1290/standings">Положение</a></li> <li><a href="/contest/1290/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e61378d58e3aeb7760ba0a66dd4c6af215aa807e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Ильдар учитель алгоритмов у Вильяма и Харриса. Сегодня, Ильдар рассказывает Декартово дерево. К сожалению, Харрис заболел, поэтому Ильдар учит сегодня только Вильяма.</p><p>Декартово дерево это корневое дерево, которое может быть построено с помощью последовательности различных целых чисел. Мы строим декартово дерево следующим образом:</p><ol><li> Если последовательность пустая, верните пустое дерево;</li><li> Пусть позиция <span class="tex-font-style-bf">максимального</span> элемента это $$$x$$$;</li><li> Удалите элемент на позиции $$$x$$$ из последовательности и разбейте ее на левую и правую часть от этого элемента (которые могут оказаться пустыми) (элемент на самом деле нужно не удалить навсегда, а временно забрать из последовательности);</li><li> Постройте декартово дерево для каждой части;</li><li> Сделайте новую вершину для элемента, который был на позиции $$$x$$$, который станет корнем всего дерева. Теперь, если корни декартовых деревьев для левой и правой части существовали, они становятся сыновьями для этой вершины;</li><li> Верните полученное дерево.</li></ol><p>Например, это декартово дерево для последовательности $$$4, 2, 7, 3, 5, 6, 1$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f877ecaa038b10e98f7ec812c49db83101751df2.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>После того, как Ильдар рассказал про декартово дерево, он задал домашнее задание. Он начинает с пустой последовательности $$$a$$$.</p><p>В $$$i$$$-м раунде, он добавляет число $$$i$$$ куда-то в $$$a$$$. Затем, он задает вопрос: чему равна сумма размеров поддеревьев для всех вершин в декартовом дереве текущей последовательности $$$a$$$?</p><p>Вершина $$$v$$$ находится в поддереве вершины $$$u$$$, тогда и только тогда, когда $$$v = u$$$ или $$$v$$$ находится в одном из поддеревьев одного из сыновей вершины $$$u$$$. Размер поддерева вершины $$$u$$$ равен количеству вершин $$$v$$$, таких что $$$v$$$ находится в поддереве вершины $$$u$$$.</p><p>Всего Ильдар проведет $$$n$$$ раундов. В качестве домашней работы он просит дать ответ на эти $$$n$$$ вопросов.</p><p>На следующий день, Ильдар сказал Харрису, что он тоже должен выполнить это домашнее задание. Харрис получил финальное состояние последовательности $$$a$$$ от Вильяма. К сожалению, у него нету идей как получить ответы на эти $$$n$$$ вопросов. Помогите Харрису!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$1 \le n \le 150000$$$).</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$). Гарантируется, что каждое целое число от $$$1$$$ до $$$n$$$ встречается в последовательности ровно один раз.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ строк, $$$i$$$-я строка должна содержать единственное целое число  — ответ на $$$i$$$-й вопрос.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 2 4 1 5 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 6 8 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 2 4 5 6 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 6 8 12 17 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>После первого раунда, последовательность это $$$1$$$. Дерево выглядит так:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1294322241a0a31b70bd01f0ecdf83a60ca83ff4.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Ответ равен $$$1$$$.</p><p>После второго раунда, последовательность это $$$2, 1$$$. Дерево выглядит так:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f85f7d3bf9bba20cffc31bfa7a60c0b9b6551b47.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Ответ равен $$$2+1=3$$$.</p><p>После третьего раунда, последовательность это $$$2, 1, 3$$$. Дерево выглядит так:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/380e5934e3aa08e48ff7aac9794081eff1d9780c.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Ответ равен $$$2+1+3=6$$$.</p><p>После четвертого раунда, последовательность это $$$2, 4, 1, 3$$$. Дерево выглядит так:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/cea423eb4d2aab92cb47bddcd5e9fd0390f0bb59.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Ответ равен $$$1+4+1+2=8$$$.</p><p>После пятого раунда, последовательность это $$$2, 4, 1, 5, 3$$$. Дерево выглядит так:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/05b17e05157251662473893bd80e02e4bdaf1869.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Ответ равен $$$1+3+1+5+1=11$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:55: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:'8124944bc9199dae',t:'MTY5NjY2NTMwMC4yMDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*3300"]
1290F
1290
F
ru
F. Построение многоугольников
<div class="problem-statement"><div class="header"><div class="title">F. Построение многоугольников</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>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>Вам дано $$$n$$$ попарно неколлинеарных двумерных векторов. Вы можете создавать замкнутые ломаные на двумерной плоскости с помощью этих векторов и следующего процесса:</p><ol><li> Вы встаете в начало координат, точку $$$(0, 0)$$$.</li><li> Выберите один из векторов и отложите отрезок из текущей точки, равный этому вектору. То есть, если ваша текущая точка имеет координаты $$$(x, y)$$$ и вы выбираете вектор $$$(u, v)$$$, нарисуйте отрезок из текущей точки в точку с координатами $$$(x + u, y + v)$$$ и встаньте в точку $$$(x + u, y + v)$$$.</li><li> Повторяйте шаг 2, пока вы не окажетесь в начале координат снова.</li></ol><p>Вы можете использовать каждый вектор любое количество раз в ходе процесса.</p><p>Посчитайте количество различных, невырожденных (площадь больше $$$0$$$), выпуклых многоугольников, которые могут быть получены этим процессом и такие, что они могут быть помещены в квадрат размером $$$m \times m$$$ и вектора, использованные для построения многоугольника, идут в порядке против часовой стрелки. Поскольку это количество может быть слишком большим вы должны найти его по модулю $$$998244353$$$.</p><p>Два многоугольника считаются одинаковыми, если существует параллельный перенос одного из многоугольников, переводящий его в другой.</p><p>Многоугольник можно поместить в квадрат размером $$$m \times m$$$, если существует параллельный перенос этого многоугольника, при котором любая точка $$$(u, v)$$$ внутри или на границе получившегося многоугольника удовлетворяет неравенствам $$$0 \leq u, v \leq m$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$  — количество векторов и размер квадрата ($$$1 \leq n \leq 5$$$, $$$1 \leq m \leq 10^9$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит два целых числа $$$x_i$$$ и $$$y_i$$$  — $$$x$$$-координата и $$$y$$$-координата $$$i$$$-о вектора ($$$|x_i|, |y_i| \leq 4$$$, $$$(x_i, y_i) \neq (0, 0)$$$).</p><p>Гарантируется, что никакие два данных вектора не параллельны, то есть для любых двух индексов $$$i$$$ и $$$j$$$, таких что $$$1 \leq i &lt; j \leq n$$$, не существует вещественного числа $$$k$$$, такого что $$$x_i \cdot k = x_j$$$ и $$$y_i \cdot k = y_j$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число  — количество многоугольников, удовлетворяющих всем условиям по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 -1 0 1 1 0 -1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 -1 0 2 2 0 -1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1776966 -1 0 3 3 0 -2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 296161 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 15 -4 -4 -1 1 -1 -4 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 10 3 -4 4 -3 1 -3 2 -3 -3 -4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1000000000 -2 4 2 -3 0 -4 2 4 -1 -3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9248783 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Многоугольники для первого теста:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/428c5a52ec121ba14e0e8ea418953109eaf42136.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Единственный многоугольник для второго теста:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1fde4bb989dfab032a22cd8205fe8a031471c2ae.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Единственный многоугольник для четвертого теста:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d5f96e7251356986f597e502192eb6313de7b0dd.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="b0f8d7b92779b58f710fc7ca64283885"/> <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="08675d1611244d997fc00a21cd5df84da1c60370"/> <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='b0f8d7b92779b58f710fc7ca64283885'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1290%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='b0f8d7b92779b58f710fc7ca64283885'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1290">Codeforces Round 616 (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='b0f8d7b92779b58f710fc7ca64283885'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1290/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound 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='b0f8d7b92779b58f710fc7ca64283885'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="529282"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b0f8d7b92779b58f710fc7ca64283885'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="529282"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73462" title="Codeforces Round #616" target="_blank">Codeforces Round #616 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10335" resourceName="Codeforces Round #616" resourceManual="true" src="//codeforces.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/73563" title="Codeforces Round #616 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10345" resourceName="Codeforces Round #616 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/1290">Задачи</a></li> <li><a href="/contest/1290/submit">Отослать</a></li> <li><a href="/contest/1290/my">Мои посылки</a></li> <li><a href="/contest/1290/status">Статус</a></li> <li><a href="/contest/1290/hacks">Взломы</a></li> <li><a href="/contest/1290/room/1">Комната</a></li> <li><a href="/contest/1290/standings">Положение</a></li> <li><a href="/contest/1290/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9ac9289a8386688d498a261a7292e1b7e39fcbcb"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Построение многоугольников</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>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>Вам дано $$$n$$$ попарно неколлинеарных двумерных векторов. Вы можете создавать замкнутые ломаные на двумерной плоскости с помощью этих векторов и следующего процесса:</p><ol><li> Вы встаете в начало координат, точку $$$(0, 0)$$$.</li><li> Выберите один из векторов и отложите отрезок из текущей точки, равный этому вектору. То есть, если ваша текущая точка имеет координаты $$$(x, y)$$$ и вы выбираете вектор $$$(u, v)$$$, нарисуйте отрезок из текущей точки в точку с координатами $$$(x + u, y + v)$$$ и встаньте в точку $$$(x + u, y + v)$$$.</li><li> Повторяйте шаг 2, пока вы не окажетесь в начале координат снова.</li></ol><p>Вы можете использовать каждый вектор любое количество раз в ходе процесса.</p><p>Посчитайте количество различных, невырожденных (площадь больше $$$0$$$), выпуклых многоугольников, которые могут быть получены этим процессом и такие, что они могут быть помещены в квадрат размером $$$m \times m$$$ и вектора, использованные для построения многоугольника, идут в порядке против часовой стрелки. Поскольку это количество может быть слишком большим вы должны найти его по модулю $$$998244353$$$.</p><p>Два многоугольника считаются одинаковыми, если существует параллельный перенос одного из многоугольников, переводящий его в другой.</p><p>Многоугольник можно поместить в квадрат размером $$$m \times m$$$, если существует параллельный перенос этого многоугольника, при котором любая точка $$$(u, v)$$$ внутри или на границе получившегося многоугольника удовлетворяет неравенствам $$$0 \leq u, v \leq m$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$  — количество векторов и размер квадрата ($$$1 \leq n \leq 5$$$, $$$1 \leq m \leq 10^9$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит два целых числа $$$x_i$$$ и $$$y_i$$$  — $$$x$$$-координата и $$$y$$$-координата $$$i$$$-о вектора ($$$|x_i|, |y_i| \leq 4$$$, $$$(x_i, y_i) \neq (0, 0)$$$).</p><p>Гарантируется, что никакие два данных вектора не параллельны, то есть для любых двух индексов $$$i$$$ и $$$j$$$, таких что $$$1 \leq i &lt; j \leq n$$$, не существует вещественного числа $$$k$$$, такого что $$$x_i \cdot k = x_j$$$ и $$$y_i \cdot k = y_j$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число  — количество многоугольников, удовлетворяющих всем условиям по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 -1 0 1 1 0 -1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 -1 0 2 2 0 -1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1776966 -1 0 3 3 0 -2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 296161 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 15 -4 -4 -1 1 -1 -4 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 10 3 -4 4 -3 1 -3 2 -3 -3 -4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1000000000 -2 4 2 -3 0 -4 2 4 -1 -3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9248783 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Многоугольники для первого теста:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/428c5a52ec121ba14e0e8ea418953109eaf42136.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Единственный многоугольник для второго теста:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1fde4bb989dfab032a22cd8205fe8a031471c2ae.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Единственный многоугольник для четвертого теста:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d5f96e7251356986f597e502192eb6313de7b0dd.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:55: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:'81249455ff914985',t:'MTY5NjY2NTMwMS41MDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1291A
1291
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>, если сумма его цифр делится на $$$2$$$, тогда как само число не делится на $$$2$$$. Например, числа $$$13$$$, $$$1227$$$, $$$185217$$$ являются <span class="tex-font-style-it">неопределенными</span>, а числа $$$2$$$, $$$12$$$, $$$177013$$$, $$$265918$$$ — нет. Для лучшего понимания этого определения посмотрите в пояснения к примерам.</p><p>Вам дано неотрицательное целое число $$$s$$$, состоящее из $$$n$$$ цифр. Вы можете удалить некоторые его цифры (они не обязательно идут подряд), чтобы получить <span class="tex-font-style-it">неопределенное</span> число. Вы не можете менять порядок цифр, то есть после удаления цифр из числа оставшиеся цифры просто схлопываются. Получившееся число должно не содержать ведущие нули. Количество удаляемых цифр может быть любым от $$$0$$$ (вы вообще не удаляете цифры) до $$$n-1$$$.</p><p>Например, если было задано целое число $$$s=$$$<span class="tex-font-style-tt">222373204424185217171912</span>, то один из способов сделать его <span class="tex-font-style-it">неопределенным</span> имеет вид: <span class="tex-font-style-tt"><span class="tex-font-style-bf"><span class="tex-font-style-striked">2</span></span>22373<span class="tex-font-style-bf"><span class="tex-font-style-striked">20</span></span>442<span class="tex-font-style-bf"><span class="tex-font-style-striked">4</span></span>18521717191<span class="tex-font-style-bf"><span class="tex-font-style-striked">2</span></span></span> $$$\rightarrow$$$ <span class="tex-font-style-tt">2237344218521717191</span>. Сумма цифр числа <span class="tex-font-style-tt">2237344218521717191</span> равна $$$70$$$ и делится на $$$2$$$, но само число на $$$2$$$ не делится — значит это число является <span class="tex-font-style-it">неопределенным</span>.</p><p>Найдите <span class="tex-font-style-bf">любое</span> число, которое может получиться таким образом и является <span class="tex-font-style-it">неопределенным</span>. Если получить таким способом <span class="tex-font-style-it">неопределенное</span> число невозможно, то сообщите об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат один или несколько наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 1000$$$)  — количество наборов входных данных. В следующих строках находятся их описания.</p><p>Первая строка описания каждого набора входных данных содержит единственное целое число $$$n$$$ ($$$1 \le n \le 3000$$$)  — количество цифр данного числа.</p><p>Во второй строке описания каждого набора входных данных содержится неотрицательное целое число $$$s$$$, состоящее из $$$n$$$ цифр.</p><p>Гарантируется, что $$$s$$$ не содержит ведущих нулей и что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$3000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите ответ в следующем формате:</p><ul><li> Если невозможно получить <span class="tex-font-style-it">неопределенное</span> число, выведите «<span class="tex-font-style-tt">-1</span>» (без кавычек).</li><li> Иначе, выведите получившееся число, после удаления некоторых, возможно нуля, но не всех цифр данного числа. Это число должно являться <span class="tex-font-style-it">неопределенным</span>. Если существует несколько возможных ответов, вы можете вывести <span class="tex-font-style-bf">любой</span> из них. Обратите внимание, что числа, содержащие ведущие нули или пустая строка не являются верными ответами. <span class="tex-font-style-bf">Количество удаленных цифр не нужно минимизировать или максимизировать, вы можете найти любой ответ, подходящий под условие</span>.</li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 1227 1 0 6 177013 24 222373204424185217171912 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1227 -1 17703 2237344218521717191 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, $$$1227$$$ уже является <span class="tex-font-style-it">неопределенным</span> числом ($$$1 + 2 + 2 + 7 = 12$$$. Число $$$12$$$ делится на $$$2$$$, тогда как число $$$1227$$$ не делится на $$$2$$$), поэтому можно не удалять цифры. Такие ответы, как $$$127$$$ и $$$17$$$ тоже являются верными.</p><p>Во втором тестовом случае, очевидно, что невозможно получить <span class="tex-font-style-it">неопределенное</span> число из данного числа.</p><p>В третьем тестовом случае, существует много <span class="tex-font-style-it">неопределенных</span> чисел, которые мы можем получить с помощью удаления некоторых цифр. Например при удалении $$$1$$$ цифры это числа $$$17703$$$, $$$77013$$$ или $$$17013$$$. Ответы, такие как $$$1701$$$ или $$$770$$$ не будут верными, потому что они не являются <span class="tex-font-style-it">неопределенными</span> числами. Ответ $$$013$$$ не является верным, потому что он содержит ведущие нули.</p><p>Пояснение:</p><ul><li> $$$1 + 7 + 7 + 0 + 3 = 18$$$. Так как $$$18$$$ делится на $$$2$$$, а само число $$$17703$$$ не делится на $$$2$$$, мы можем увидеть, что число $$$17703$$$ является <span class="tex-font-style-it">неопределенным</span> числом. Тоже самое верно для чисел $$$77013$$$ и $$$17013$$$;</li><li> $$$1 + 7 + 0 + 1 = 9$$$. Так как $$$9$$$ не делится на $$$2$$$, число $$$1701$$$ не является <span class="tex-font-style-it">неопределенным</span> числом;</li><li> $$$7 + 7 + 0 = 14$$$. В этот раз, $$$14$$$ делится на $$$2$$$, но само число $$$770$$$ также делится на $$$2$$$, поэтому число $$$770$$$ не является <span class="tex-font-style-it">неопределенным</span>.</li></ul><p>В последнем наборе входных данных примера продемонстрирован один из множества возможных ответов. Другой возможный ответ: <span class="tex-font-style-tt">222373204424185217171912</span> $$$\rightarrow$$$ <span class="tex-font-style-tt">22237320442418521717191</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="eba9ad362e96cd420d77a3338212d674"/> <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="7f7c8edb305ad1a489f28783eb5154c5aad0bbf4"/> <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='eba9ad362e96cd420d77a3338212d674'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1291%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='eba9ad362e96cd420d77a3338212d674'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1291">Codeforces Round 616 (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='eba9ad362e96cd420d77a3338212d674'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1291/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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="Сложность"> *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='eba9ad362e96cd420d77a3338212d674'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="529283"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='eba9ad362e96cd420d77a3338212d674'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="529283"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73462" title="Codeforces Round #616" target="_blank">Codeforces Round #616 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10336" resourceName="Codeforces Round #616" resourceManual="true" src="//codeforces.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/73563" title="Codeforces Round #616 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10346" resourceName="Codeforces Round #616 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/1291">Задачи</a></li> <li><a href="/contest/1291/submit">Отослать</a></li> <li><a href="/contest/1291/my">Мои посылки</a></li> <li><a href="/contest/1291/status">Статус</a></li> <li><a href="/contest/1291/hacks">Взломы</a></li> <li><a href="/contest/1291/room/1">Комната</a></li> <li><a href="/contest/1291/standings">Положение</a></li> <li><a href="/contest/1291/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a72ad4235d6430d2918d7472389d7319481e5da9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>, если сумма его цифр делится на $$$2$$$, тогда как само число не делится на $$$2$$$. Например, числа $$$13$$$, $$$1227$$$, $$$185217$$$ являются <span class="tex-font-style-it">неопределенными</span>, а числа $$$2$$$, $$$12$$$, $$$177013$$$, $$$265918$$$ — нет. Для лучшего понимания этого определения посмотрите в пояснения к примерам.</p><p>Вам дано неотрицательное целое число $$$s$$$, состоящее из $$$n$$$ цифр. Вы можете удалить некоторые его цифры (они не обязательно идут подряд), чтобы получить <span class="tex-font-style-it">неопределенное</span> число. Вы не можете менять порядок цифр, то есть после удаления цифр из числа оставшиеся цифры просто схлопываются. Получившееся число должно не содержать ведущие нули. Количество удаляемых цифр может быть любым от $$$0$$$ (вы вообще не удаляете цифры) до $$$n-1$$$.</p><p>Например, если было задано целое число $$$s=$$$<span class="tex-font-style-tt">222373204424185217171912</span>, то один из способов сделать его <span class="tex-font-style-it">неопределенным</span> имеет вид: <span class="tex-font-style-tt"><span class="tex-font-style-bf"><span class="tex-font-style-striked">2</span></span>22373<span class="tex-font-style-bf"><span class="tex-font-style-striked">20</span></span>442<span class="tex-font-style-bf"><span class="tex-font-style-striked">4</span></span>18521717191<span class="tex-font-style-bf"><span class="tex-font-style-striked">2</span></span></span> $$$\rightarrow$$$ <span class="tex-font-style-tt">2237344218521717191</span>. Сумма цифр числа <span class="tex-font-style-tt">2237344218521717191</span> равна $$$70$$$ и делится на $$$2$$$, но само число на $$$2$$$ не делится — значит это число является <span class="tex-font-style-it">неопределенным</span>.</p><p>Найдите <span class="tex-font-style-bf">любое</span> число, которое может получиться таким образом и является <span class="tex-font-style-it">неопределенным</span>. Если получить таким способом <span class="tex-font-style-it">неопределенное</span> число невозможно, то сообщите об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат один или несколько наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 1000$$$)  — количество наборов входных данных. В следующих строках находятся их описания.</p><p>Первая строка описания каждого набора входных данных содержит единственное целое число $$$n$$$ ($$$1 \le n \le 3000$$$)  — количество цифр данного числа.</p><p>Во второй строке описания каждого набора входных данных содержится неотрицательное целое число $$$s$$$, состоящее из $$$n$$$ цифр.</p><p>Гарантируется, что $$$s$$$ не содержит ведущих нулей и что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$3000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите ответ в следующем формате:</p><ul><li> Если невозможно получить <span class="tex-font-style-it">неопределенное</span> число, выведите «<span class="tex-font-style-tt">-1</span>» (без кавычек).</li><li> Иначе, выведите получившееся число, после удаления некоторых, возможно нуля, но не всех цифр данного числа. Это число должно являться <span class="tex-font-style-it">неопределенным</span>. Если существует несколько возможных ответов, вы можете вывести <span class="tex-font-style-bf">любой</span> из них. Обратите внимание, что числа, содержащие ведущие нули или пустая строка не являются верными ответами. <span class="tex-font-style-bf">Количество удаленных цифр не нужно минимизировать или максимизировать, вы можете найти любой ответ, подходящий под условие</span>.</li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 1227 1 0 6 177013 24 222373204424185217171912 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1227 -1 17703 2237344218521717191 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, $$$1227$$$ уже является <span class="tex-font-style-it">неопределенным</span> числом ($$$1 + 2 + 2 + 7 = 12$$$. Число $$$12$$$ делится на $$$2$$$, тогда как число $$$1227$$$ не делится на $$$2$$$), поэтому можно не удалять цифры. Такие ответы, как $$$127$$$ и $$$17$$$ тоже являются верными.</p><p>Во втором тестовом случае, очевидно, что невозможно получить <span class="tex-font-style-it">неопределенное</span> число из данного числа.</p><p>В третьем тестовом случае, существует много <span class="tex-font-style-it">неопределенных</span> чисел, которые мы можем получить с помощью удаления некоторых цифр. Например при удалении $$$1$$$ цифры это числа $$$17703$$$, $$$77013$$$ или $$$17013$$$. Ответы, такие как $$$1701$$$ или $$$770$$$ не будут верными, потому что они не являются <span class="tex-font-style-it">неопределенными</span> числами. Ответ $$$013$$$ не является верным, потому что он содержит ведущие нули.</p><p>Пояснение:</p><ul><li> $$$1 + 7 + 7 + 0 + 3 = 18$$$. Так как $$$18$$$ делится на $$$2$$$, а само число $$$17703$$$ не делится на $$$2$$$, мы можем увидеть, что число $$$17703$$$ является <span class="tex-font-style-it">неопределенным</span> числом. Тоже самое верно для чисел $$$77013$$$ и $$$17013$$$;</li><li> $$$1 + 7 + 0 + 1 = 9$$$. Так как $$$9$$$ не делится на $$$2$$$, число $$$1701$$$ не является <span class="tex-font-style-it">неопределенным</span> числом;</li><li> $$$7 + 7 + 0 = 14$$$. В этот раз, $$$14$$$ делится на $$$2$$$, но само число $$$770$$$ также делится на $$$2$$$, поэтому число $$$770$$$ не является <span class="tex-font-style-it">неопределенным</span>.</li></ul><p>В последнем наборе входных данных примера продемонстрирован один из множества возможных ответов. Другой возможный ответ: <span class="tex-font-style-tt">222373204424185217171912</span> $$$\rightarrow$$$ <span class="tex-font-style-tt">22237320442418521717191</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:55: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:'8124945e1fb61411',t:'MTY5NjY2NTMwMi45MTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u0442\u0440\u043e\u043a\u0438", "*900"]
1291B
1291
B
ru
B. Заострение массива
<div class="problem-statement"><div class="header"><div class="title">B. Заострение массива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив $$$a_1, \ldots, a_n$$$ из $$$n$$$ неотрицательных целых чисел.</p><p>Назовем его <span class="tex-font-style-it">заостренным</span>, если существует целое число $$$1 \le k \le n$$$, такое что $$$a_1 &lt; a_2 &lt; \ldots &lt; a_k$$$ и $$$a_k &gt; a_{k+1} &gt; \ldots &gt; a_n$$$. В частности, любой строго возрастающий или строго убывающий массив является <span class="tex-font-style-it">заостренным</span>. Например:</p><ul> <li> Массивы $$$[4]$$$, $$$[0, 1]$$$, $$$[12, 10, 8]$$$ и $$$[3, 11, 15, 9, 7, 4]$$$ являются заостренными; </li><li> Массивы $$$[2, 8, 2, 8, 6, 5]$$$, $$$[0, 1, 1, 0]$$$ и $$$[2, 5, 6, 9, 8, 8]$$$ <span class="tex-font-style-bf">не</span> являются заостренными. </li></ul><p>Вы можете сделать следующую операцию, сколько угодно раз: выбрать любой <span class="tex-font-style-bf">строго положительный</span> элемент массива и уменьшить его на единицу. Формально, вы можете выбрать любой индекс $$$i$$$ ($$$1 \le i \le n$$$), такой что $$$a_i&gt;0$$$, и выполнить присвоение $$$a_i := a_i - 1$$$.</p><p>Определите, возможно ли сделать данный массив <span class="tex-font-style-it">заостренным</span>, сделав некоторое количество (возможно ноль) этих операций.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат несколько тестовых случаев. В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 15\ 000$$$)  — количество тестовых случаев. В следующих строках находится их описание.</p><p>В первой строке описания каждого тестового случая находится единственное целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$).</p><p>Во второй строке описания каждого тестового случая находится последовательность из $$$n$$$ целых неотрицательных чисел $$$a_1, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).</p><p>Гарантируется, что сумма значений $$$n$$$ по всем тестовым случаям не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите единственную строку, содержащую «<span class="tex-font-style-tt">Yes</span>» (без кавычек), если возможно сделать данный массив заостренным, используя описанные операции, или «<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> 10 1 248618 3 12 10 8 6 100 11 15 9 7 8 4 0 1 1 0 2 0 0 2 0 1 2 1 0 2 1 1 3 0 1 0 3 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes Yes Yes No No Yes Yes Yes Yes No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом и втором тестовых случаях первого теста, данный массив уже является заостренным.</p><p>В третьем тестовом случае первого теста, мы можем получить массив $$$[3, 11, 15, 9, 7, 4]$$$ (уменьшить первый элемент $$$97$$$ раз и уменьшить последний элемент $$$4$$$ раза). Он заостренный, потому что $$$3 &lt; 11 &lt; 15$$$ и $$$15 &gt; 9 &gt; 7 &gt; 4$$$.</p><p>В четвертом тестовом случае первого теста, невозможно сделать массив заостренным.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="dd629f970af0644d2eb2f52387639241"/> <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="7f7c8edb305ad1a489f28783eb5154c5aad0bbf4"/> <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='dd629f970af0644d2eb2f52387639241'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1291%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='dd629f970af0644d2eb2f52387639241'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1291">Codeforces Round 616 (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='dd629f970af0644d2eb2f52387639241'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1291/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='dd629f970af0644d2eb2f52387639241'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="529284"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='dd629f970af0644d2eb2f52387639241'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="529284"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73462" title="Codeforces Round #616" target="_blank">Codeforces Round #616 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10336" resourceName="Codeforces Round #616" resourceManual="true" src="//codeforces.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/73563" title="Codeforces Round #616 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10346" resourceName="Codeforces Round #616 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/1291">Задачи</a></li> <li><a href="/contest/1291/submit">Отослать</a></li> <li><a href="/contest/1291/my">Мои посылки</a></li> <li><a href="/contest/1291/status">Статус</a></li> <li><a href="/contest/1291/hacks">Взломы</a></li> <li><a href="/contest/1291/room/1">Комната</a></li> <li><a href="/contest/1291/standings">Положение</a></li> <li><a href="/contest/1291/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a31be3e3be748f1917feacb54ef16e66b0859e95"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Заострение массива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив $$$a_1, \ldots, a_n$$$ из $$$n$$$ неотрицательных целых чисел.</p><p>Назовем его <span class="tex-font-style-it">заостренным</span>, если существует целое число $$$1 \le k \le n$$$, такое что $$$a_1 &lt; a_2 &lt; \ldots &lt; a_k$$$ и $$$a_k &gt; a_{k+1} &gt; \ldots &gt; a_n$$$. В частности, любой строго возрастающий или строго убывающий массив является <span class="tex-font-style-it">заостренным</span>. Например:</p><ul> <li> Массивы $$$[4]$$$, $$$[0, 1]$$$, $$$[12, 10, 8]$$$ и $$$[3, 11, 15, 9, 7, 4]$$$ являются заостренными; </li><li> Массивы $$$[2, 8, 2, 8, 6, 5]$$$, $$$[0, 1, 1, 0]$$$ и $$$[2, 5, 6, 9, 8, 8]$$$ <span class="tex-font-style-bf">не</span> являются заостренными. </li></ul><p>Вы можете сделать следующую операцию, сколько угодно раз: выбрать любой <span class="tex-font-style-bf">строго положительный</span> элемент массива и уменьшить его на единицу. Формально, вы можете выбрать любой индекс $$$i$$$ ($$$1 \le i \le n$$$), такой что $$$a_i&gt;0$$$, и выполнить присвоение $$$a_i := a_i - 1$$$.</p><p>Определите, возможно ли сделать данный массив <span class="tex-font-style-it">заостренным</span>, сделав некоторое количество (возможно ноль) этих операций.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат несколько тестовых случаев. В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 15\ 000$$$)  — количество тестовых случаев. В следующих строках находится их описание.</p><p>В первой строке описания каждого тестового случая находится единственное целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$).</p><p>Во второй строке описания каждого тестового случая находится последовательность из $$$n$$$ целых неотрицательных чисел $$$a_1, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).</p><p>Гарантируется, что сумма значений $$$n$$$ по всем тестовым случаям не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите единственную строку, содержащую «<span class="tex-font-style-tt">Yes</span>» (без кавычек), если возможно сделать данный массив заостренным, используя описанные операции, или «<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> 10 1 248618 3 12 10 8 6 100 11 15 9 7 8 4 0 1 1 0 2 0 0 2 0 1 2 1 0 2 1 1 3 0 1 0 3 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes Yes Yes No No Yes Yes Yes Yes No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом и втором тестовых случаях первого теста, данный массив уже является заостренным.</p><p>В третьем тестовом случае первого теста, мы можем получить массив $$$[3, 11, 15, 9, 7, 4]$$$ (уменьшить первый элемент $$$97$$$ раз и уменьшить последний элемент $$$4$$$ раза). Он заостренный, потому что $$$3 &lt; 11 &lt; 15$$$ и $$$15 &gt; 9 &gt; 7 &gt; 4$$$.</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:55: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:'81249466e92775af',t:'MTY5NjY2NTMwNC4yNDgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1300"]
1291C
1291
C
ru
C. Контроль сознания
<div class="problem-statement"><div class="header"><div class="title">C. Контроль сознания</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы и ваш $$$n - 1$$$ друг нашли массив целых чисел $$$a_1, a_2, \dots, a_n$$$. Вы решили разделить его следующим образом: все $$$n$$$ человек встают в линию в определенном порядке. Каждую минуту, человек в начале линии выбирает либо первый, либо последний элемент массива, удаляет его и забирает себе. Затем, он выходит из линии и процесс продолжается со следующим стоящим в линии человеком.</p><p>Вы стоите на $$$m$$$-й позиции в линии. <span class="tex-font-style-bf">Перед тем, как процесс начнется</span>, вы можете выбрать не больше чем $$$k$$$ различных людей в линии и каждого из них убедить всегда брать либо первый, либо последний элемент массива во время их хода (для каждого человека свой выбор, не обязательно у всех одинаковый), не зависимо от того, какие это элементы. <span class="tex-font-style-bf">После того, как процесс начнется, вы не сможете убедить больше людей или изменить выбор уже убежденных вами людей</span>.</p><p>Предположим, что вы сделаете ваш выбор оптимально. Чему равно максимальное целое число $$$x$$$, такое что, вне зависимости от ходов тех друзей, которых вы не выбрали, чтобы убедить, элемент массива, который вы получите на вашем ходу, будет <span class="tex-font-style-bf">не меньше, чем</span> $$$x$$$?</p><p>Обратите внимание, что друзья, которых вы не выбрали для того, чтобы убедить сделать их заранее определенный вами выбор, могут делать свой выбор <span class="tex-font-style-bf"><span class="tex-font-style-underline">произвольно</span></span> и они не обязательно будут брать наибольший доступный для них элемент.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат несколько тестовых случаев. В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 1000$$$)  — количество тестовых случаев. В следующих строках находится их описание.</p><p>В первой строке описания каждого тестового случая находятся три разделенных пробелом целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$1 \le m \le n \le 3500$$$, $$$0 \le k \le n - 1$$$)  — количество элементов в массиве, ваша позиция в линии и количество человек, чей выбор вы можете зафиксировать.</p><p>Во второй строке описания каждого тестового случая содержится $$$n$$$ положительных целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — элементы массива.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем тестовым случаям не превосходит $$$3500$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите наибольшее целое число $$$x$$$, такое что вы можете гарантировать себе получить число не меньше, чем $$$x$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 4 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, одной из оптимальных стратегий является убедить первого человека брать последний элемент и второго человека брать первый элемент.</p><ul> <li> первый человек возьмет последний элемент ($$$5$$$), потому что он или она были убеждены вами взять последний элемент. После этого хода оставшийся массив будет $$$[2, 9, 2, 3, 8]$$$; </li><li> второй человек возьмет первый элемент ($$$2$$$), потому что он или она были убеждены вами взять первый элемент. После этого хода оставшийся массив будет $$$[9, 2, 3, 8]$$$; </li><li> если третий человек выберет взять первый элемент ($$$9$$$), к вашему ходу оставшийся массив будет $$$[2, 3, 8]$$$ и вы сможете взять $$$8$$$ (последний элемент); </li><li> если третий человек выберет взять последний элемент ($$$8$$$), к вашему ходу оставшийся массив будет $$$[9, 2, 3]$$$ и вы сможете взять $$$9$$$ (первый элемент). </li></ul><p>Таким образом, эта стратегия гарантирует получить в конце число не меньше, чем $$$8$$$. Можно доказать, что не существует стратегии, гарантирующей получить число не меньше чем $$$9$$$. Таким образом, ответ равен $$$8$$$.</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="d3d0c282892e09cb4566182b61bead54"/> <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="7f7c8edb305ad1a489f28783eb5154c5aad0bbf4"/> <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='d3d0c282892e09cb4566182b61bead54'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1291%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='d3d0c282892e09cb4566182b61bead54'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1291">Codeforces Round 616 (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='d3d0c282892e09cb4566182b61bead54'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1291/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='d3d0c282892e09cb4566182b61bead54'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="529285"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d3d0c282892e09cb4566182b61bead54'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="529285"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73462" title="Codeforces Round #616" target="_blank">Codeforces Round #616 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10336" resourceName="Codeforces Round #616" resourceManual="true" src="//codeforces.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/73563" title="Codeforces Round #616 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10346" resourceName="Codeforces Round #616 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/1291">Задачи</a></li> <li><a href="/contest/1291/submit">Отослать</a></li> <li><a href="/contest/1291/my">Мои посылки</a></li> <li><a href="/contest/1291/status">Статус</a></li> <li><a href="/contest/1291/hacks">Взломы</a></li> <li><a href="/contest/1291/room/1">Комната</a></li> <li><a href="/contest/1291/standings">Положение</a></li> <li><a href="/contest/1291/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ea0a7392db90d8001e9f26450217e05ac2c2cea3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Контроль сознания</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы и ваш $$$n - 1$$$ друг нашли массив целых чисел $$$a_1, a_2, \dots, a_n$$$. Вы решили разделить его следующим образом: все $$$n$$$ человек встают в линию в определенном порядке. Каждую минуту, человек в начале линии выбирает либо первый, либо последний элемент массива, удаляет его и забирает себе. Затем, он выходит из линии и процесс продолжается со следующим стоящим в линии человеком.</p><p>Вы стоите на $$$m$$$-й позиции в линии. <span class="tex-font-style-bf">Перед тем, как процесс начнется</span>, вы можете выбрать не больше чем $$$k$$$ различных людей в линии и каждого из них убедить всегда брать либо первый, либо последний элемент массива во время их хода (для каждого человека свой выбор, не обязательно у всех одинаковый), не зависимо от того, какие это элементы. <span class="tex-font-style-bf">После того, как процесс начнется, вы не сможете убедить больше людей или изменить выбор уже убежденных вами людей</span>.</p><p>Предположим, что вы сделаете ваш выбор оптимально. Чему равно максимальное целое число $$$x$$$, такое что, вне зависимости от ходов тех друзей, которых вы не выбрали, чтобы убедить, элемент массива, который вы получите на вашем ходу, будет <span class="tex-font-style-bf">не меньше, чем</span> $$$x$$$?</p><p>Обратите внимание, что друзья, которых вы не выбрали для того, чтобы убедить сделать их заранее определенный вами выбор, могут делать свой выбор <span class="tex-font-style-bf"><span class="tex-font-style-underline">произвольно</span></span> и они не обязательно будут брать наибольший доступный для них элемент.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат несколько тестовых случаев. В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 1000$$$)  — количество тестовых случаев. В следующих строках находится их описание.</p><p>В первой строке описания каждого тестового случая находятся три разделенных пробелом целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$1 \le m \le n \le 3500$$$, $$$0 \le k \le n - 1$$$)  — количество элементов в массиве, ваша позиция в линии и количество человек, чей выбор вы можете зафиксировать.</p><p>Во второй строке описания каждого тестового случая содержится $$$n$$$ положительных целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — элементы массива.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем тестовым случаям не превосходит $$$3500$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая, выведите наибольшее целое число $$$x$$$, такое что вы можете гарантировать себе получить число не меньше, чем $$$x$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 4 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, одной из оптимальных стратегий является убедить первого человека брать последний элемент и второго человека брать первый элемент.</p><ul> <li> первый человек возьмет последний элемент ($$$5$$$), потому что он или она были убеждены вами взять последний элемент. После этого хода оставшийся массив будет $$$[2, 9, 2, 3, 8]$$$; </li><li> второй человек возьмет первый элемент ($$$2$$$), потому что он или она были убеждены вами взять первый элемент. После этого хода оставшийся массив будет $$$[9, 2, 3, 8]$$$; </li><li> если третий человек выберет взять первый элемент ($$$9$$$), к вашему ходу оставшийся массив будет $$$[2, 3, 8]$$$ и вы сможете взять $$$8$$$ (последний элемент); </li><li> если третий человек выберет взять последний элемент ($$$8$$$), к вашему ходу оставшийся массив будет $$$[9, 2, 3]$$$ и вы сможете взять $$$9$$$ (первый элемент). </li></ul><p>Таким образом, эта стратегия гарантирует получить в конце число не меньше, чем $$$8$$$. Можно доказать, что не существует стратегии, гарантирующей получить число не меньше чем $$$9$$$. Таким образом, ответ равен $$$8$$$.</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:55: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:'8124946fabd316e8',t:'MTY5NjY2NTMwNS42MTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1600"]
1291D
1291
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$$$ и $$$t$$$ <span class="tex-font-style-it">анаграммами</span> друг друга, если можно так переставить символы в строке $$$s$$$, чтобы получить строку, равную $$$t$$$.</p><p>Рассмотрим две строки $$$s$$$ и $$$t$$$, <span class="tex-font-style-bf">являющиеся анаграммами друг друга</span>. Будем говорить, что $$$t$$$ это <span class="tex-font-style-it">приводимая анаграмма</span> строки $$$s$$$, если существует такое целое число $$$k \ge 2$$$ и $$$2k$$$ непустых строк $$$s_1, t_1, s_2, t_2, \dots, s_k, t_k$$$, которые удовлетворяют следующим условиям:</p><ol> <li> Если мы запишем в линию строки $$$s_1, s_2, \dots, s_k$$$ в таком порядке, то получившаяся строка будет равна $$$s$$$; </li><li> Если мы запишем в линию строки $$$t_1, t_2, \dots, t_k$$$ в таком порядке, то получившаяся строка будет равна $$$t$$$; </li><li> Для всех целых $$$i$$$ между $$$1$$$ и $$$k$$$ включительно, $$$s_i$$$ и $$$t_i$$$ являются анаграммами. </li></ol><p>Если таких строк не существует, тогда $$$t$$$ называется <span class="tex-font-style-it">неприводимой анаграммой</span> строки $$$s$$$. <span class="tex-font-style-bf">Обратите внимание, что этот термин определяется только в случае, когда $$$s$$$ и $$$t$$$ это анаграммы</span>.</p><p>Например, рассмотрим строку $$$s = $$$ «<span class="tex-font-style-tt">gamegame</span>». Тогда строка $$$t = $$$ «<span class="tex-font-style-tt">megamage</span>» это приводимая анаграмма для $$$s$$$, потому что мы можем выбрать, например, $$$s_1 = $$$ «<span class="tex-font-style-tt">game</span>», $$$s_2 = $$$ «<span class="tex-font-style-tt">gam</span>», $$$s_3 = $$$ «<span class="tex-font-style-tt">e</span>» и $$$t_1 = $$$ «<span class="tex-font-style-tt">mega</span>», $$$t_2 = $$$ «<span class="tex-font-style-tt">mag</span>», $$$t_3 = $$$ «<span class="tex-font-style-tt">e</span>»:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/62af0aaee3571a1f20e5fd483333e25ef163e0c2.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>С другой стороны, можно показать, что $$$t = $$$ «<span class="tex-font-style-tt">memegaga</span>» это неприводимая анаграмма для $$$s$$$.</p><p>Вам будет дана строка $$$s$$$ и $$$q$$$ запросов, каждый представляется двумя целыми числами $$$1 \le l \le r \le |s|$$$ (где за $$$|s|$$$ обозначается длина строки $$$s$$$). Для каждого запроса, вы должны определить, имеет ли подстрока строки $$$s$$$, с $$$l$$$-о по $$$r$$$-й символ, включительно, <span class="tex-font-style-underline"> хотя бы одну</span> неприводимую анаграмму.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится строка $$$s$$$, состоящая из строчных символов латинского алфавита ($$$1 \le |s| \le 2 \cdot 10^5$$$).</p><p>Во второй строке содержится единственное целое число $$$q$$$ ($$$1 \le q \le 10^5$$$)  — количество запросов.</p><p>Следующие $$$q$$$ строк содержат по два целых числа $$$l$$$ и $$$r$$$ ($$$1 \le l \le r \le |s|$$$), обозначающие очередной запрос для подстроки $$$s$$$, состоящей из символов с $$$l$$$-о по $$$r$$$-й.</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> aaaaa 3 1 1 2 4 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No Yes </pre></div><div class="input"><div class="title">Входные данные</div><pre> aabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No Yes Yes Yes No No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, в первом и третьем запросах, подстрока будет «<span class="tex-font-style-tt">a</span>» и она имеет саму себя как неприводимую анаграмму, так как две и больше непустые строки, записанные вместе, не смогут дать строку «<span class="tex-font-style-tt">a</span>». С другой стороны, во втором запросе, подстрока будет «<span class="tex-font-style-tt">aaa</span>», которая не имеет неприводимых анаграмм: ее единственная анаграмма это она сама и мы можем выбрать $$$s_1 = $$$ «<span class="tex-font-style-tt">a</span>», $$$s_2 = $$$ «<span class="tex-font-style-tt">aa</span>», $$$t_1 = $$$ «<span class="tex-font-style-tt">a</span>», $$$t_2 = $$$ «<span class="tex-font-style-tt">aa</span>», чтобы показать, что это приводимая анаграмма.</p><p>Во втором запросе второго тестового случая, подстрока будет «<span class="tex-font-style-tt">abb</span>» и она имеет, например, неприводимую анаграмму «<span class="tex-font-style-tt">bba</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="e11b588d426f399a819f8af50a784da3"/> <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="7f7c8edb305ad1a489f28783eb5154c5aad0bbf4"/> <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='e11b588d426f399a819f8af50a784da3'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1291%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='e11b588d426f399a819f8af50a784da3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1291">Codeforces Round 616 (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='e11b588d426f399a819f8af50a784da3'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1291/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *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='e11b588d426f399a819f8af50a784da3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="529287"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e11b588d426f399a819f8af50a784da3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="529287"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73462" title="Codeforces Round #616" target="_blank">Codeforces Round #616 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10336" resourceName="Codeforces Round #616" resourceManual="true" src="//codeforces.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/73563" title="Codeforces Round #616 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10346" resourceName="Codeforces Round #616 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/1291">Задачи</a></li> <li><a href="/contest/1291/submit">Отослать</a></li> <li><a href="/contest/1291/my">Мои посылки</a></li> <li><a href="/contest/1291/status">Статус</a></li> <li><a href="/contest/1291/hacks">Взломы</a></li> <li><a href="/contest/1291/room/1">Комната</a></li> <li><a href="/contest/1291/standings">Положение</a></li> <li><a href="/contest/1291/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4dabdd07e40724c22ef8d17be81fa360410d4f09"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ и $$$t$$$ <span class="tex-font-style-it">анаграммами</span> друг друга, если можно так переставить символы в строке $$$s$$$, чтобы получить строку, равную $$$t$$$.</p><p>Рассмотрим две строки $$$s$$$ и $$$t$$$, <span class="tex-font-style-bf">являющиеся анаграммами друг друга</span>. Будем говорить, что $$$t$$$ это <span class="tex-font-style-it">приводимая анаграмма</span> строки $$$s$$$, если существует такое целое число $$$k \ge 2$$$ и $$$2k$$$ непустых строк $$$s_1, t_1, s_2, t_2, \dots, s_k, t_k$$$, которые удовлетворяют следующим условиям:</p><ol> <li> Если мы запишем в линию строки $$$s_1, s_2, \dots, s_k$$$ в таком порядке, то получившаяся строка будет равна $$$s$$$; </li><li> Если мы запишем в линию строки $$$t_1, t_2, \dots, t_k$$$ в таком порядке, то получившаяся строка будет равна $$$t$$$; </li><li> Для всех целых $$$i$$$ между $$$1$$$ и $$$k$$$ включительно, $$$s_i$$$ и $$$t_i$$$ являются анаграммами. </li></ol><p>Если таких строк не существует, тогда $$$t$$$ называется <span class="tex-font-style-it">неприводимой анаграммой</span> строки $$$s$$$. <span class="tex-font-style-bf">Обратите внимание, что этот термин определяется только в случае, когда $$$s$$$ и $$$t$$$ это анаграммы</span>.</p><p>Например, рассмотрим строку $$$s = $$$ «<span class="tex-font-style-tt">gamegame</span>». Тогда строка $$$t = $$$ «<span class="tex-font-style-tt">megamage</span>» это приводимая анаграмма для $$$s$$$, потому что мы можем выбрать, например, $$$s_1 = $$$ «<span class="tex-font-style-tt">game</span>», $$$s_2 = $$$ «<span class="tex-font-style-tt">gam</span>», $$$s_3 = $$$ «<span class="tex-font-style-tt">e</span>» и $$$t_1 = $$$ «<span class="tex-font-style-tt">mega</span>», $$$t_2 = $$$ «<span class="tex-font-style-tt">mag</span>», $$$t_3 = $$$ «<span class="tex-font-style-tt">e</span>»:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/62af0aaee3571a1f20e5fd483333e25ef163e0c2.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>С другой стороны, можно показать, что $$$t = $$$ «<span class="tex-font-style-tt">memegaga</span>» это неприводимая анаграмма для $$$s$$$.</p><p>Вам будет дана строка $$$s$$$ и $$$q$$$ запросов, каждый представляется двумя целыми числами $$$1 \le l \le r \le |s|$$$ (где за $$$|s|$$$ обозначается длина строки $$$s$$$). Для каждого запроса, вы должны определить, имеет ли подстрока строки $$$s$$$, с $$$l$$$-о по $$$r$$$-й символ, включительно, <span class="tex-font-style-underline"> хотя бы одну</span> неприводимую анаграмму.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится строка $$$s$$$, состоящая из строчных символов латинского алфавита ($$$1 \le |s| \le 2 \cdot 10^5$$$).</p><p>Во второй строке содержится единственное целое число $$$q$$$ ($$$1 \le q \le 10^5$$$)  — количество запросов.</p><p>Следующие $$$q$$$ строк содержат по два целых числа $$$l$$$ и $$$r$$$ ($$$1 \le l \le r \le |s|$$$), обозначающие очередной запрос для подстроки $$$s$$$, состоящей из символов с $$$l$$$-о по $$$r$$$-й.</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> aaaaa 3 1 1 2 4 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No Yes </pre></div><div class="input"><div class="title">Входные данные</div><pre> aabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No Yes Yes Yes No No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, в первом и третьем запросах, подстрока будет «<span class="tex-font-style-tt">a</span>» и она имеет саму себя как неприводимую анаграмму, так как две и больше непустые строки, записанные вместе, не смогут дать строку «<span class="tex-font-style-tt">a</span>». С другой стороны, во втором запросе, подстрока будет «<span class="tex-font-style-tt">aaa</span>», которая не имеет неприводимых анаграмм: ее единственная анаграмма это она сама и мы можем выбрать $$$s_1 = $$$ «<span class="tex-font-style-tt">a</span>», $$$s_2 = $$$ «<span class="tex-font-style-tt">aa</span>», $$$t_1 = $$$ «<span class="tex-font-style-tt">a</span>», $$$t_2 = $$$ «<span class="tex-font-style-tt">aa</span>», чтобы показать, что это приводимая анаграмма.</p><p>Во втором запросе второго тестового случая, подстрока будет «<span class="tex-font-style-tt">abb</span>» и она имеет, например, неприводимую анаграмму «<span class="tex-font-style-tt">bba</span>».</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:55: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:'81249477bcf30c4e',t:'MTY5NjY2NTMwNi45MjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\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.", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u0442\u0440\u043e\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1800"]
1291E
1291
E
ru
E. Освещение префиксов
<div class="problem-statement"><div class="header"><div class="title">E. Освещение префиксов</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В линию было расположено $$$n$$$ ламп, пронумерованных целыми числами от $$$1$$$ до $$$n$$$. Каждая лампа изначально либо выключена ($$$0$$$) или включена ($$$1$$$).</p><p>Вам дано $$$k$$$ подмножеств $$$A_1, \ldots, A_k$$$ множества ламп $$$\{1, 2, \dots, n\}$$$, таких что пересечение любых трех подмножеств пусто. Другими словами, для всех $$$1 \le i_1 &lt; i_2 &lt; i_3 \le k$$$ выполнено $$$A_{i_1} \cap A_{i_2} \cap A_{i_3} = \varnothing$$$.</p><p>За одну операцию вы можете выбрать одно из этих $$$k$$$ подмножеств и изменить состояние всех ламп из этого подмножества (выключенные лампы становятся включенными, включенные становятся выключенными). Гарантируется, что для данных подмножеств можно совершить несколько операций так, чтобы все лампы стали включенными.</p><p>Обозначим за $$$m_i$$$ минимальное количество операций, которое вы должны совершить, чтобы первые $$$i$$$ ламп оказались включенными. Обратите внимание, что при этом состояние других ламп (с номерами между $$$i+1$$$ и $$$n$$$) может быть любым.</p><p>Посчитайте $$$m_i$$$ для всех $$$1 \le i \le n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 3 \cdot 10^5$$$).</p><p>Во второй строке находится двоичная строка длины $$$n$$$, обозначающая начальное состояние каждой лампы (лампа $$$i$$$ выключена, если $$$s_i = 0$$$, включена, если $$$s_i = 1$$$).</p><p>Описание каждого из $$$k$$$ подмножеств следует, в следующем формате:</p><p>В первой строке описания находится единственное целое число $$$c$$$ ($$$1 \le c \le n$$$)  — количество элементов в подмножестве.</p><p>Во второй строке описания находится $$$c$$$ различных целых чисел $$$x_1, \ldots, x_c$$$ ($$$1 \le x_i \le n$$$)  — элементы подмножества.</p><p>Гарантируется, что:</p><ul> <li> Пересечение любых трех подмножеств пусто; </li><li> С помощью нескольких операций можно сделать все лампы одновременно включенными. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести $$$n$$$ строк. В $$$i$$$-й строке должно содержаться единственное целое число $$$m_i$$$  — минимальное количество операций, необходимое для того чтобы сделать все лампы с номерами от $$$1$$$ до $$$i$$$ включенными. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 3 3 3 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 1 4 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 00011 3 1 2 3 1 4 3 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте: </p><ul> <li> Для $$$i = 1$$$, мы можем сделать одну операцию с множеством $$$A_1$$$, итоговые состояния будут $$$1010110$$$; </li><li> Для $$$i = 2$$$, мы можем сделать операции с множествами $$$A_1$$$ и $$$A_3$$$, итоговые состояния будут $$$1100110$$$; </li><li> For $$$i \ge 3$$$, we can apply operations on $$$A_1$$$, $$$A_2$$$ and $$$A_3$$$, the final states will be $$$1111111$$$. </li></ul><p>Во втором тесте: </p><ul> <li> Для $$$i \le 6$$$, мы можем просто сделать одну операцию с множеством $$$A_2$$$, итоговые состояния будут $$$11111101$$$; </li><li> Для $$$i \ge 7$$$, мы можем сделать операции с множествами $$$A_1, A_3, A_4, A_6$$$, итоговые состояния будут $$$11111111$$$. </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="bfa8ec99260f387d9ff94b92a9c2e2ac"/> <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="7f7c8edb305ad1a489f28783eb5154c5aad0bbf4"/> <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='bfa8ec99260f387d9ff94b92a9c2e2ac'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1291%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='bfa8ec99260f387d9ff94b92a9c2e2ac'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1291">Codeforces Round 616 (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='bfa8ec99260f387d9ff94b92a9c2e2ac'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1291/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств"> снм </span> </div> <div class="roundbox borderTopRound 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='bfa8ec99260f387d9ff94b92a9c2e2ac'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="529286"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bfa8ec99260f387d9ff94b92a9c2e2ac'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="529286"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73462" title="Codeforces Round #616" target="_blank">Codeforces Round #616 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10336" resourceName="Codeforces Round #616" resourceManual="true" src="//codeforces.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/73563" title="Codeforces Round #616 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10346" resourceName="Codeforces Round #616 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/1291">Задачи</a></li> <li><a href="/contest/1291/submit">Отослать</a></li> <li><a href="/contest/1291/my">Мои посылки</a></li> <li><a href="/contest/1291/status">Статус</a></li> <li><a href="/contest/1291/hacks">Взломы</a></li> <li><a href="/contest/1291/room/1">Комната</a></li> <li><a href="/contest/1291/standings">Положение</a></li> <li><a href="/contest/1291/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_304039eced77c30973af38da3bccbb05cfb37708"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Освещение префиксов</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В линию было расположено $$$n$$$ ламп, пронумерованных целыми числами от $$$1$$$ до $$$n$$$. Каждая лампа изначально либо выключена ($$$0$$$) или включена ($$$1$$$).</p><p>Вам дано $$$k$$$ подмножеств $$$A_1, \ldots, A_k$$$ множества ламп $$$\{1, 2, \dots, n\}$$$, таких что пересечение любых трех подмножеств пусто. Другими словами, для всех $$$1 \le i_1 &lt; i_2 &lt; i_3 \le k$$$ выполнено $$$A_{i_1} \cap A_{i_2} \cap A_{i_3} = \varnothing$$$.</p><p>За одну операцию вы можете выбрать одно из этих $$$k$$$ подмножеств и изменить состояние всех ламп из этого подмножества (выключенные лампы становятся включенными, включенные становятся выключенными). Гарантируется, что для данных подмножеств можно совершить несколько операций так, чтобы все лампы стали включенными.</p><p>Обозначим за $$$m_i$$$ минимальное количество операций, которое вы должны совершить, чтобы первые $$$i$$$ ламп оказались включенными. Обратите внимание, что при этом состояние других ламп (с номерами между $$$i+1$$$ и $$$n$$$) может быть любым.</p><p>Посчитайте $$$m_i$$$ для всех $$$1 \le i \le n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 3 \cdot 10^5$$$).</p><p>Во второй строке находится двоичная строка длины $$$n$$$, обозначающая начальное состояние каждой лампы (лампа $$$i$$$ выключена, если $$$s_i = 0$$$, включена, если $$$s_i = 1$$$).</p><p>Описание каждого из $$$k$$$ подмножеств следует, в следующем формате:</p><p>В первой строке описания находится единственное целое число $$$c$$$ ($$$1 \le c \le n$$$)  — количество элементов в подмножестве.</p><p>Во второй строке описания находится $$$c$$$ различных целых чисел $$$x_1, \ldots, x_c$$$ ($$$1 \le x_i \le n$$$)  — элементы подмножества.</p><p>Гарантируется, что:</p><ul> <li> Пересечение любых трех подмножеств пусто; </li><li> С помощью нескольких операций можно сделать все лампы одновременно включенными. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести $$$n$$$ строк. В $$$i$$$-й строке должно содержаться единственное целое число $$$m_i$$$  — минимальное количество операций, необходимое для того чтобы сделать все лампы с номерами от $$$1$$$ до $$$i$$$ включенными. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 3 3 3 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 1 4 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 00011 3 1 2 3 1 4 3 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте: </p><ul> <li> Для $$$i = 1$$$, мы можем сделать одну операцию с множеством $$$A_1$$$, итоговые состояния будут $$$1010110$$$; </li><li> Для $$$i = 2$$$, мы можем сделать операции с множествами $$$A_1$$$ и $$$A_3$$$, итоговые состояния будут $$$1100110$$$; </li><li> For $$$i \ge 3$$$, we can apply operations on $$$A_1$$$, $$$A_2$$$ and $$$A_3$$$, the final states will be $$$1111111$$$. </li></ul><p>Во втором тесте: </p><ul> <li> Для $$$i \le 6$$$, мы можем просто сделать одну операцию с множеством $$$A_2$$$, итоговые состояния будут $$$11111101$$$; </li><li> Для $$$i \ge 7$$$, мы можем сделать операции с множествами $$$A_1, A_3, A_4, A_6$$$, итоговые состояния будут $$$11111111$$$. </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:55: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:'8124947fe930160a',t:'MTY5NjY2NTMwOC4yOTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u043d\u043c", "*2400"]
1291F
1291
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><span class="tex-font-style-it">Это простая версия задачи. Вы можете найти сложную версию в Div. 1 контесте. Обе версии отличаются только в ограничении на количество раз, которое вы можете попросить вашего друга попробовать кофе.</span></p><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Вы собираетесь поехать в другой город, где живет один из ваших друзей. В этом городе $$$n$$$ кафе, где число $$$n$$$ является степенью двойки. В $$$i$$$-м кафе варят кофе сорта $$$a_i$$$.</p><p>Поскольку вы большой любитель кофе, перед тем, как выбрать поехать ли в этот город или нет, <span class="tex-font-style-bf">вы хотите узнать количество различных сортов кофе $$$d$$$</span>, которое варят в этом городе.</p><p>Вы не знаете значений $$$a_1, \ldots, a_n$$$. К счастью, ваш друг хорошо запоминает события последних $$$k$$$ дней, где $$$k$$$ это степень двойки.</p><p>Каждый день, вы можете попросить его попробовать чашечку кофе, сваренного в кафе с номером $$$c$$$ и он скажет, пробовал ли он кофе того же сорта в последние $$$k$$$ дней.</p><p>Также вы можете попросить его забыть все, что он пробовал до этого. После этого он забудет все предыдущие разы, когда он пробовал кофе. Вы можете делать это не больше $$$30\ 000$$$ раз.</p><p>Более формально, память вашего друга это некоторая очередь $$$S$$$. Сделать запрос сходить попробовать кофе в кафе с номером $$$c$$$ означает: </p><ul> <li> Сказать вам, есть ли $$$a_c$$$ в $$$S$$$; </li><li> Добавить $$$a_c$$$ в конец очереди $$$S$$$; </li><li> Если $$$|S| &gt; k$$$, удалить первый элемент очереди $$$S$$$. </li></ul><p>Запрос забывания всех посещений кафе удаляет все элементы очереди $$$S$$$, то есть отчищает ее.</p><p>Вы можете попросить вашего друга попробовать не больше $$$\dfrac{2n^2}{k}$$$ чашек кофе. Найдите разнообразность города $$$d$$$ (количество различных значений в массиве $$$a$$$).</p><p>Обратите внимание, что попросить вашего друга забыть все походы в кафе, что были до этого <span class="tex-font-style-bf">не считается</span> среди количества запросов попросить вашего друга попробовать кофе.</p><p>В некоторых тестах поведение интерактора будет <span class="tex-font-style-bf">адаптивным</span>. Это означает, что массив $$$a$$$ может быть <span class="tex-font-style-bf">не фиксированным</span> до начала тестирования вашей программы и <span class="tex-font-style-bf">может зависеть от ваших запросов</span>. Гарантируется, что в любой момент тестирования, существует хотя бы один массив $$$a$$$, для которого верны все данные до этого ответы на запросы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 1024$$$, $$$k$$$ и $$$n$$$ это степени двойки).</p><p>Гарантируется, что $$$\dfrac{2n^2}{k} \le 20\ 000$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Вы начинаете взаимодействие со считывания двух чисел $$$n$$$ и $$$k$$$.</p><ul><li> Для того, чтобы попросить вашего друга попробовать чашечку кофе в кафе с номером $$$c$$$, в отдельной строке выведите<p><span class="tex-font-style-tt">? $$$c$$$</span></p><p>Тут $$$c$$$ должно удовлетворять условиям $$$1 \le c \le n$$$. Не забывайте сделать сброс буфера потока вывода после этого.</p><p>В ответ вы получите символ <span class="tex-font-style-tt">Y</span> (да) или <span class="tex-font-style-tt">N</span> (нет), сообщающий вам, встречался ли сорт кофе $$$a_c$$$ среди последних $$$k$$$ сортов кофе в памяти вашего друга.</p></li><li> Для того чтобы отчистить память вашего друга, в отдельной строке выведите единственный символ <span class="tex-font-style-tt">R</span> (<span class="tex-font-style-bf">большая латинская буква</span>). Вы можете сделать этот запрос не более $$$30\ 000$$$ раз.</li><li> После того, как вы определили количество $$$d$$$ различных сортов кофе, выведите<p><span class="tex-font-style-tt">! $$$d$$$</span></p></li></ul><p>В случае, если запрос, сделанный вами, некорректный или вы сделали больше, чем $$$\frac{2n^2}{k}$$$ запросов типа <span class="tex-font-style-tt">?</span> или больше, чем $$$30\ 000$$$ запросов типа <span class="tex-font-style-tt">R</span>, в ответ тестирующая программа выведет символ <span class="tex-font-style-tt">E</span> и закончит тестирование. Вы получите вердикт <span class="tex-font-style-bf">Wrong Answer</span>. Будьте осторожны, для этого ваша программа должна немедленно завершиться в этом случае, иначе вердикт посылки может быть любым.</p><p>После вывода запроса не забывайте переводить строку и делать сброс буфера потока вывода. Иначе, вы получите вердикт <span class="tex-font-style-bf">Idleness limit exceeded</span>. Для того, чтобы сделать сброс буфера потока вывода, используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> обратитесь к документации для остальных языков. </li></ul><p><span class="tex-font-style-bf">Взломы</span></p><p>В первой строке теста должно находиться слово <span class="tex-font-style-tt">fixed</span></p><p>Во второй строке должны содержаться два целых числа $$$n$$$ и $$$k$$$, разделенных пробелом ($$$1 \le k \le n \le 1024$$$, $$$k$$$ и $$$n$$$ это степени двойки).</p><p>Должно быть выполнено, что $$$\dfrac{2n^2}{k} \le 20\ 000$$$.</p><p>В третьей строке должны содержаться $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$, разделенных пробелом ($$$1 \le a_i \le 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 2 N N Y N N N N </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 ? 2 ? 3 ? 4 R ? 4 ? 1 ? 2 ! 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 8 N N N N Y Y </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 2 ? 6 ? 4 ? 5 ? 2 ? 5 ! 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, массив $$$a = [1, 4, 1, 3]$$$. В городе производится $$$3$$$ различных сорта кофе ($$$1$$$, $$$3$$$ и $$$4$$$).</p><p>Последовательные сорта кофе, попробованные вашим другом это $$$1, 4, \textbf{1}, 3, 3, 1, 4$$$ (жирным выделены запросы с ответом <span class="tex-font-style-tt">Y</span>). Обратите внимание, что между двумя запросами <span class="tex-font-style-tt">? 4</span>, был запрос отчищения памяти, поэтому ответ на второй запрос <span class="tex-font-style-tt">? 4</span> был <span class="tex-font-style-tt">N</span>. Если бы этого запроса не было, то ответ на второй запрос <span class="tex-font-style-tt">? 4</span> был бы <span class="tex-font-style-tt">Y</span>.</p><p>Во втором тесте, массив $$$a = [1, 2, 3, 4, 5, 6, 6, 6]$$$. В городе производится $$$6$$$ различных сортов кофе.</p><p>Последовательные сорта кофе, попробованные вашим другом это $$$2, 6, 4, 5, \textbf{2}, \textbf{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="3c1c3b605b91c1c76efd8908ef0e6877"/> <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="7f7c8edb305ad1a489f28783eb5154c5aad0bbf4"/> <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='3c1c3b605b91c1c76efd8908ef0e6877'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1291%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='3c1c3b605b91c1c76efd8908ef0e6877'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1291">Codeforces Round 616 (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='3c1c3b605b91c1c76efd8908ef0e6877'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1291/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3c1c3b605b91c1c76efd8908ef0e6877'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="529294"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3c1c3b605b91c1c76efd8908ef0e6877'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="529294"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73462" title="Codeforces Round #616" target="_blank">Codeforces Round #616 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10336" resourceName="Codeforces Round #616" resourceManual="true" src="//codeforces.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/73563" title="Codeforces Round #616 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10346" resourceName="Codeforces Round #616 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/1291">Задачи</a></li> <li><a href="/contest/1291/submit">Отослать</a></li> <li><a href="/contest/1291/my">Мои посылки</a></li> <li><a href="/contest/1291/status">Статус</a></li> <li><a href="/contest/1291/hacks">Взломы</a></li> <li><a href="/contest/1291/room/1">Комната</a></li> <li><a href="/contest/1291/standings">Положение</a></li> <li><a href="/contest/1291/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_df03fe9b5b083b3dfd4e9660290f551850afe600"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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><span class="tex-font-style-it">Это простая версия задачи. Вы можете найти сложную версию в Div. 1 контесте. Обе версии отличаются только в ограничении на количество раз, которое вы можете попросить вашего друга попробовать кофе.</span></p><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Вы собираетесь поехать в другой город, где живет один из ваших друзей. В этом городе $$$n$$$ кафе, где число $$$n$$$ является степенью двойки. В $$$i$$$-м кафе варят кофе сорта $$$a_i$$$.</p><p>Поскольку вы большой любитель кофе, перед тем, как выбрать поехать ли в этот город или нет, <span class="tex-font-style-bf">вы хотите узнать количество различных сортов кофе $$$d$$$</span>, которое варят в этом городе.</p><p>Вы не знаете значений $$$a_1, \ldots, a_n$$$. К счастью, ваш друг хорошо запоминает события последних $$$k$$$ дней, где $$$k$$$ это степень двойки.</p><p>Каждый день, вы можете попросить его попробовать чашечку кофе, сваренного в кафе с номером $$$c$$$ и он скажет, пробовал ли он кофе того же сорта в последние $$$k$$$ дней.</p><p>Также вы можете попросить его забыть все, что он пробовал до этого. После этого он забудет все предыдущие разы, когда он пробовал кофе. Вы можете делать это не больше $$$30\ 000$$$ раз.</p><p>Более формально, память вашего друга это некоторая очередь $$$S$$$. Сделать запрос сходить попробовать кофе в кафе с номером $$$c$$$ означает: </p><ul> <li> Сказать вам, есть ли $$$a_c$$$ в $$$S$$$; </li><li> Добавить $$$a_c$$$ в конец очереди $$$S$$$; </li><li> Если $$$|S| &gt; k$$$, удалить первый элемент очереди $$$S$$$. </li></ul><p>Запрос забывания всех посещений кафе удаляет все элементы очереди $$$S$$$, то есть отчищает ее.</p><p>Вы можете попросить вашего друга попробовать не больше $$$\dfrac{2n^2}{k}$$$ чашек кофе. Найдите разнообразность города $$$d$$$ (количество различных значений в массиве $$$a$$$).</p><p>Обратите внимание, что попросить вашего друга забыть все походы в кафе, что были до этого <span class="tex-font-style-bf">не считается</span> среди количества запросов попросить вашего друга попробовать кофе.</p><p>В некоторых тестах поведение интерактора будет <span class="tex-font-style-bf">адаптивным</span>. Это означает, что массив $$$a$$$ может быть <span class="tex-font-style-bf">не фиксированным</span> до начала тестирования вашей программы и <span class="tex-font-style-bf">может зависеть от ваших запросов</span>. Гарантируется, что в любой момент тестирования, существует хотя бы один массив $$$a$$$, для которого верны все данные до этого ответы на запросы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 1024$$$, $$$k$$$ и $$$n$$$ это степени двойки).</p><p>Гарантируется, что $$$\dfrac{2n^2}{k} \le 20\ 000$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Вы начинаете взаимодействие со считывания двух чисел $$$n$$$ и $$$k$$$.</p><ul><li> Для того, чтобы попросить вашего друга попробовать чашечку кофе в кафе с номером $$$c$$$, в отдельной строке выведите<p><span class="tex-font-style-tt">? $$$c$$$</span></p><p>Тут $$$c$$$ должно удовлетворять условиям $$$1 \le c \le n$$$. Не забывайте сделать сброс буфера потока вывода после этого.</p><p>В ответ вы получите символ <span class="tex-font-style-tt">Y</span> (да) или <span class="tex-font-style-tt">N</span> (нет), сообщающий вам, встречался ли сорт кофе $$$a_c$$$ среди последних $$$k$$$ сортов кофе в памяти вашего друга.</p></li><li> Для того чтобы отчистить память вашего друга, в отдельной строке выведите единственный символ <span class="tex-font-style-tt">R</span> (<span class="tex-font-style-bf">большая латинская буква</span>). Вы можете сделать этот запрос не более $$$30\ 000$$$ раз.</li><li> После того, как вы определили количество $$$d$$$ различных сортов кофе, выведите<p><span class="tex-font-style-tt">! $$$d$$$</span></p></li></ul><p>В случае, если запрос, сделанный вами, некорректный или вы сделали больше, чем $$$\frac{2n^2}{k}$$$ запросов типа <span class="tex-font-style-tt">?</span> или больше, чем $$$30\ 000$$$ запросов типа <span class="tex-font-style-tt">R</span>, в ответ тестирующая программа выведет символ <span class="tex-font-style-tt">E</span> и закончит тестирование. Вы получите вердикт <span class="tex-font-style-bf">Wrong Answer</span>. Будьте осторожны, для этого ваша программа должна немедленно завершиться в этом случае, иначе вердикт посылки может быть любым.</p><p>После вывода запроса не забывайте переводить строку и делать сброс буфера потока вывода. Иначе, вы получите вердикт <span class="tex-font-style-bf">Idleness limit exceeded</span>. Для того, чтобы сделать сброс буфера потока вывода, используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> обратитесь к документации для остальных языков. </li></ul><p><span class="tex-font-style-bf">Взломы</span></p><p>В первой строке теста должно находиться слово <span class="tex-font-style-tt">fixed</span></p><p>Во второй строке должны содержаться два целых числа $$$n$$$ и $$$k$$$, разделенных пробелом ($$$1 \le k \le n \le 1024$$$, $$$k$$$ и $$$n$$$ это степени двойки).</p><p>Должно быть выполнено, что $$$\dfrac{2n^2}{k} \le 20\ 000$$$.</p><p>В третьей строке должны содержаться $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$, разделенных пробелом ($$$1 \le a_i \le 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 2 N N Y N N N N </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 ? 2 ? 3 ? 4 R ? 4 ? 1 ? 2 ! 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 8 N N N N Y Y </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 2 ? 6 ? 4 ? 5 ? 2 ? 5 ! 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, массив $$$a = [1, 4, 1, 3]$$$. В городе производится $$$3$$$ различных сорта кофе ($$$1$$$, $$$3$$$ и $$$4$$$).</p><p>Последовательные сорта кофе, попробованные вашим другом это $$$1, 4, \textbf{1}, 3, 3, 1, 4$$$ (жирным выделены запросы с ответом <span class="tex-font-style-tt">Y</span>). Обратите внимание, что между двумя запросами <span class="tex-font-style-tt">? 4</span>, был запрос отчищения памяти, поэтому ответ на второй запрос <span class="tex-font-style-tt">? 4</span> был <span class="tex-font-style-tt">N</span>. Если бы этого запроса не было, то ответ на второй запрос <span class="tex-font-style-tt">? 4</span> был бы <span class="tex-font-style-tt">Y</span>.</p><p>Во втором тесте, массив $$$a = [1, 2, 3, 4, 5, 6, 6, 6]$$$. В городе производится $$$6$$$ различных сортов кофе.</p><p>Последовательные сорта кофе, попробованные вашим другом это $$$2, 6, 4, 5, \textbf{2}, \textbf{5}$$$.</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:55: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:'8124948878949d63',t:'MTY5NjY2NTMwOS42NDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "*2800"]
1292A
1292
A
ru
A. Игровой лабиринт Неко
<div class="problem-statement"><div class="header"><div class="title">A. Игровой лабиринт Неко</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>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"><a href="https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak"><span class="tex-font-style-it">3R2 as DJ Mashiro - Happiness Breeze</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive"><span class="tex-font-style-it">Ice - DJ Mashiro is dead or alive</span></a></div></div><p>NEKO#ΦωΦ только что купила новую игру на свой компьютер!</p><p>Главный пазл этой игры это прямоугольный лабиринт $$$2 \times n$$$. Неко должна провести Некомими девочку из клетки $$$(1, 1)$$$ в клетку $$$(2, n)$$$, тем самым выбравшись из лабиринта. Девочка может переходить только между клетками, соседними по стороне.</p><p>Однако, в некоторые моменты игры, некоторые клетки меняют своё состояние: или из земли в лаву (которая не позволяет проходить через клетку), или наоборот (что делает клетку проходимой вновь). Изначально ни в одной клетке лавы нет.</p><p>Спустя часы стриминга Неко выяснила, что есть всего $$$q$$$ таких моментов, причём $$$i$$$-й из них переключает состояние клетки $$$(r_i, c_i)$$$ (с земли на лаву, или наоборот). Неко хочет узнать для каждого момента из этих $$$q$$$, можно ли после него пройти из клетки $$$(1, 1)$$$ в $$$(2, n)$$$ не проходя через клетки с лавой.</p><p>Неко великий игрок и стример, но она всё ещё не справляется с пазлами и задачками, требующими большой силы мозга. Не могли бы вы ей помочь?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$, $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$).</p><p>Среди следующих $$$q$$$ строк, $$$i$$$-я содержит целые числа $$$r_i$$$, $$$c_i$$$ ($$$1 \le r_i \le 2$$$, $$$1 \le c_i \le n$$$), обозначающие координаты клетки, меняющейся в $$$i$$$-й момент.</p><p>Гарантируется, что клетки $$$(1, 1)$$$ и $$$(2, n)$$$ никогда не будут даны в списке запросов.</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>» в зависимости от того, можно ли пройти от клетки $$$(1, 1)$$$ до $$$(2, n)$$$. Всего вам нужно вывести ровно $$$q$$$ ответов, по одному после каждого изменения.</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 2 3 1 4 2 4 2 3 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No No No Yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Разберём пример из условия:</p><ul> <li> После первого запроса девочка всё ещё может достичь цели, один из возможных путей выглядит как $$$(1,1) \to (1,2) \to (1,3) \to (1,4) \to (1,5) \to (2,5)$$$. </li><li> После второго запроса, добраться до цели невозможно, самая дальняя клетка, которой она может достичь, это $$$(1, 3)$$$. </li><li> После четвёртого запроса, клетка $$$(2, 3)$$$ уже не заблокирована, однако теперь заблокирован весь $$$4$$$-й столбец, так что достичь цели не получится. </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="673d4a8b5cc34446fce1eb555627c139"/> <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="f41d2ac68ef00d0c5fdf5706d652ecfeab2320ff"/> <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='673d4a8b5cc34446fce1eb555627c139'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1292%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='673d4a8b5cc34446fce1eb555627c139'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1292">Codeforces Round 614 (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='673d4a8b5cc34446fce1eb555627c139'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1292/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств"> снм </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='673d4a8b5cc34446fce1eb555627c139'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="519776"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='673d4a8b5cc34446fce1eb555627c139'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="519776"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69012" title="Codeforces Round #614" target="_blank">Codeforces Round #614 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10302" resourceName="Codeforces Round #614" resourceManual="true" src="//codeforces.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/73051" title="Codeforces Round #614 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10313" resourceName="Codeforces Round #614 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/1292">Задачи</a></li> <li><a href="/contest/1292/submit">Отослать</a></li> <li><a href="/contest/1292/my">Мои посылки</a></li> <li><a href="/contest/1292/status">Статус</a></li> <li><a href="/contest/1292/hacks">Взломы</a></li> <li><a href="/contest/1292/room/1">Комната</a></li> <li><a href="/contest/1292/standings">Положение</a></li> <li><a href="/contest/1292/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5bf08be68dc077a7fcfb48680c30756cbcdebcff"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Игровой лабиринт Неко</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>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"><a href="https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak"><span class="tex-font-style-it">3R2 as DJ Mashiro - Happiness Breeze</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive"><span class="tex-font-style-it">Ice - DJ Mashiro is dead or alive</span></a></div></div><p>NEKO#ΦωΦ только что купила новую игру на свой компьютер!</p><p>Главный пазл этой игры это прямоугольный лабиринт $$$2 \times n$$$. Неко должна провести Некомими девочку из клетки $$$(1, 1)$$$ в клетку $$$(2, n)$$$, тем самым выбравшись из лабиринта. Девочка может переходить только между клетками, соседними по стороне.</p><p>Однако, в некоторые моменты игры, некоторые клетки меняют своё состояние: или из земли в лаву (которая не позволяет проходить через клетку), или наоборот (что делает клетку проходимой вновь). Изначально ни в одной клетке лавы нет.</p><p>Спустя часы стриминга Неко выяснила, что есть всего $$$q$$$ таких моментов, причём $$$i$$$-й из них переключает состояние клетки $$$(r_i, c_i)$$$ (с земли на лаву, или наоборот). Неко хочет узнать для каждого момента из этих $$$q$$$, можно ли после него пройти из клетки $$$(1, 1)$$$ в $$$(2, n)$$$ не проходя через клетки с лавой.</p><p>Неко великий игрок и стример, но она всё ещё не справляется с пазлами и задачками, требующими большой силы мозга. Не могли бы вы ей помочь?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$, $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$).</p><p>Среди следующих $$$q$$$ строк, $$$i$$$-я содержит целые числа $$$r_i$$$, $$$c_i$$$ ($$$1 \le r_i \le 2$$$, $$$1 \le c_i \le n$$$), обозначающие координаты клетки, меняющейся в $$$i$$$-й момент.</p><p>Гарантируется, что клетки $$$(1, 1)$$$ и $$$(2, n)$$$ никогда не будут даны в списке запросов.</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>» в зависимости от того, можно ли пройти от клетки $$$(1, 1)$$$ до $$$(2, n)$$$. Всего вам нужно вывести ровно $$$q$$$ ответов, по одному после каждого изменения.</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 2 3 1 4 2 4 2 3 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No No No Yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Разберём пример из условия:</p><ul> <li> После первого запроса девочка всё ещё может достичь цели, один из возможных путей выглядит как $$$(1,1) \to (1,2) \to (1,3) \to (1,4) \to (1,5) \to (2,5)$$$. </li><li> После второго запроса, добраться до цели невозможно, самая дальняя клетка, которой она может достичь, это $$$(1, 3)$$$. </li><li> После четвёртого запроса, клетка $$$(2, 3)$$$ уже не заблокирована, однако теперь заблокирован весь $$$4$$$-й столбец, так что достичь цели не получится. </li><li> После пятого запроса, проблемы со столбцом пропадают, так что она снова может добраться до цели. </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:55: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:'812494910d6e4991',t:'MTY5NjY2NTMxMS4wOTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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"]
["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043d\u043c", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1400"]
1292B
1292
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><div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/hyouryu"><span class="tex-font-style-it">THE SxPLAY &amp; KIVΛ - 漂流</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/perspectives"><span class="tex-font-style-it">KIVΛ &amp; Nikki Simmons - Perspectives</span></a></div></div><p>С новым телом наш идол Арома Белая (или лучше было сказать Каори Минамийа?) начинает восстанавливать своё потерянное прошлое через OS-пространство.</p><p>Это пространство можно представить как 2D плоскость, с бесконечным количеством устройств с данными, пронумерованных с $$$0$$$. Координаты устройств можно описать следующим образом:</p><ul> <li> Координаты $$$0$$$-го устройства равны $$$(x_0, y_0)$$$ </li><li> Для $$$i &gt; 0$$$, координаты $$$i$$$-го устройства равны $$$(a_x \cdot x_{i-1} + b_x, a_y \cdot y_{i-1} + b_y)$$$ </li></ul><p>Изначально Арома расположена в точке $$$(x_s, y_s)$$$. Она может находиться в OS-пространстве не более $$$t$$$ секунд, после этого ей придётся вернуться в реальный мир. Чтобы вернутся в реальный мир <span class="tex-font-style-bf">не требуется</span> возвращаться в изначальную точку $$$(x_s, y_s)$$$.</p><p>Внутри OS-пространства Арома может делать следующие действия:</p><ul> <li> Из точки $$$(x, y)$$$ Арома может перейти в одну из следующих точек $$$(x-1, y)$$$, $$$(x+1, y)$$$, $$$(x, y-1)$$$ или $$$(x, y+1)$$$. Это действие занимает $$$1$$$ секунду. </li><li> Если Арома стоит в точке с устройством, то она может его собрать. Можно считать, что это действие занимает $$$0$$$ секунд. Разумеется, каждое устройство можно собрать не более одного раза. </li></ul><p>Арома хочет собрать как можно больше данных перед тем как вернётся назад. Помогите ей определить максимальное количество устройств с данными, которые она сможет собрать за $$$t$$$ секунд.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$x_0$$$, $$$y_0$$$, $$$a_x$$$, $$$a_y$$$, $$$b_x$$$, $$$b_y$$$ ($$$1 \leq x_0, y_0 \leq 10^{16}$$$, $$$2 \leq a_x, a_y \leq 100$$$, $$$0 \leq b_x, b_y \leq 10^{16}$$$), которые задают координаты устройств с данными.</p><p>Вторая строка содержит целые числа $$$x_s$$$, $$$y_s$$$, $$$t$$$ ($$$1 \leq x_s, y_s, t \leq 10^{16}$$$), изначальные координаты Аромы и доступное время.</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> 1 1 2 3 1 0 2 4 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3</pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 2 3 1 0 15 27 26 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 2 3 1 0 2 2 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>Во всех трёх примерах, координаты первых $$$5$$$ устройств равны $$$(1, 1)$$$, $$$(3, 3)$$$, $$$(7, 9)$$$, $$$(15, 27)$$$ и $$$(31, 81)$$$ (напомним, что устройства пронумерованы начиная с $$$0$$$).</p><p>В первом примере оптимальный маршрут чтобы собрать $$$3$$$ вершины выглядит следующим образом: </p><ul> <li> Перейти в точку $$$(3, 3)$$$ и собрать $$$1$$$-е устройство. Это занимает $$$|3 - 2| + |3 - 4| = 2$$$ секунд. </li><li> Перейти в точку $$$(1, 1)$$$ и собрать $$$0$$$-е устройство. Это занимает $$$|1 - 3| + |1 - 3| = 4$$$ секунд. </li><li> Перейти в точку $$$(7, 9)$$$ и собрать $$$2$$$-е устройство. Это занимает $$$|7 - 1| + |9 - 1| = 14$$$ секунд. </li></ul><p>Во втором примере оптимальный маршрут чтобы собрать $$$2$$$ вершины выглядит следующим образом: </p><ul> <li> Собрать $$$3$$$-е устройство. Это занимает ноль секунд. </li><li> Перейти в точку $$$(7, 9)$$$ и собрать $$$2$$$-е устройство. Это занимает $$$|15 - 7| + |27 - 9| = 26$$$ секунд. </li></ul><p>В третьем примере Арома не может собрать ни одного устройства. Пожалуй стоило отдохнуть, а не рваться в OS-пространство без подготовки.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="e6e443e6870e766cc92f097f92930df2"/> <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="f41d2ac68ef00d0c5fdf5706d652ecfeab2320ff"/> <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='e6e443e6870e766cc92f097f92930df2'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1292%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='e6e443e6870e766cc92f097f92930df2'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1292">Codeforces Round 614 (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='e6e443e6870e766cc92f097f92930df2'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1292/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Геометрия"> геометрия </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='e6e443e6870e766cc92f097f92930df2'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="519777"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e6e443e6870e766cc92f097f92930df2'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="519777"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69012" title="Codeforces Round #614" target="_blank">Codeforces Round #614 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10302" resourceName="Codeforces Round #614" resourceManual="true" src="//codeforces.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/73051" title="Codeforces Round #614 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10313" resourceName="Codeforces Round #614 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/1292">Задачи</a></li> <li><a href="/contest/1292/submit">Отослать</a></li> <li><a href="/contest/1292/my">Мои посылки</a></li> <li><a href="/contest/1292/status">Статус</a></li> <li><a href="/contest/1292/hacks">Взломы</a></li> <li><a href="/contest/1292/room/1">Комната</a></li> <li><a href="/contest/1292/standings">Положение</a></li> <li><a href="/contest/1292/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_23bd753697e4dad63638131fb2284bc26b99e30f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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><div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/hyouryu"><span class="tex-font-style-it">THE SxPLAY &amp; KIVΛ - 漂流</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/perspectives"><span class="tex-font-style-it">KIVΛ &amp; Nikki Simmons - Perspectives</span></a></div></div><p>С новым телом наш идол Арома Белая (или лучше было сказать Каори Минамийа?) начинает восстанавливать своё потерянное прошлое через OS-пространство.</p><p>Это пространство можно представить как 2D плоскость, с бесконечным количеством устройств с данными, пронумерованных с $$$0$$$. Координаты устройств можно описать следующим образом:</p><ul> <li> Координаты $$$0$$$-го устройства равны $$$(x_0, y_0)$$$ </li><li> Для $$$i &gt; 0$$$, координаты $$$i$$$-го устройства равны $$$(a_x \cdot x_{i-1} + b_x, a_y \cdot y_{i-1} + b_y)$$$ </li></ul><p>Изначально Арома расположена в точке $$$(x_s, y_s)$$$. Она может находиться в OS-пространстве не более $$$t$$$ секунд, после этого ей придётся вернуться в реальный мир. Чтобы вернутся в реальный мир <span class="tex-font-style-bf">не требуется</span> возвращаться в изначальную точку $$$(x_s, y_s)$$$.</p><p>Внутри OS-пространства Арома может делать следующие действия:</p><ul> <li> Из точки $$$(x, y)$$$ Арома может перейти в одну из следующих точек $$$(x-1, y)$$$, $$$(x+1, y)$$$, $$$(x, y-1)$$$ или $$$(x, y+1)$$$. Это действие занимает $$$1$$$ секунду. </li><li> Если Арома стоит в точке с устройством, то она может его собрать. Можно считать, что это действие занимает $$$0$$$ секунд. Разумеется, каждое устройство можно собрать не более одного раза. </li></ul><p>Арома хочет собрать как можно больше данных перед тем как вернётся назад. Помогите ей определить максимальное количество устройств с данными, которые она сможет собрать за $$$t$$$ секунд.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$x_0$$$, $$$y_0$$$, $$$a_x$$$, $$$a_y$$$, $$$b_x$$$, $$$b_y$$$ ($$$1 \leq x_0, y_0 \leq 10^{16}$$$, $$$2 \leq a_x, a_y \leq 100$$$, $$$0 \leq b_x, b_y \leq 10^{16}$$$), которые задают координаты устройств с данными.</p><p>Вторая строка содержит целые числа $$$x_s$$$, $$$y_s$$$, $$$t$$$ ($$$1 \leq x_s, y_s, t \leq 10^{16}$$$), изначальные координаты Аромы и доступное время.</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> 1 1 2 3 1 0 2 4 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3</pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 2 3 1 0 15 27 26 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 2 3 1 0 2 2 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>Во всех трёх примерах, координаты первых $$$5$$$ устройств равны $$$(1, 1)$$$, $$$(3, 3)$$$, $$$(7, 9)$$$, $$$(15, 27)$$$ и $$$(31, 81)$$$ (напомним, что устройства пронумерованы начиная с $$$0$$$).</p><p>В первом примере оптимальный маршрут чтобы собрать $$$3$$$ вершины выглядит следующим образом: </p><ul> <li> Перейти в точку $$$(3, 3)$$$ и собрать $$$1$$$-е устройство. Это занимает $$$|3 - 2| + |3 - 4| = 2$$$ секунд. </li><li> Перейти в точку $$$(1, 1)$$$ и собрать $$$0$$$-е устройство. Это занимает $$$|1 - 3| + |1 - 3| = 4$$$ секунд. </li><li> Перейти в точку $$$(7, 9)$$$ и собрать $$$2$$$-е устройство. Это занимает $$$|7 - 1| + |9 - 1| = 14$$$ секунд. </li></ul><p>Во втором примере оптимальный маршрут чтобы собрать $$$2$$$ вершины выглядит следующим образом: </p><ul> <li> Собрать $$$3$$$-е устройство. Это занимает ноль секунд. </li><li> Перейти в точку $$$(7, 9)$$$ и собрать $$$2$$$-е устройство. Это занимает $$$|15 - 7| + |27 - 9| = 26$$$ секунд. </li></ul><p>В третьем примере Арома не может собрать ни одного устройства. Пожалуй стоило отдохнуть, а не рваться в OS-пространство без подготовки.</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:55:12</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'8124949a09f70c54',t:'MTY5NjY2NTMxMi40NTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1700"]
1292C
1292
C
ru
C. Атака Ксенона
<div class="problem-statement"><div class="header"><div class="title">C. Атака Ксенона</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><div class="epigraph"><div class="epigraph-text"><a href="https://www.youtube.com/watch?v=kwsciXm_7sA"><span class="tex-font-style-it">INSPION FullBand Master - INSPION</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://www.youtube.com/watch?v=kwsciXm_7sA"><span class="tex-font-style-it">INSPION - IOLITE-SUNSTONE</span></a></div></div><p>На другом этаже A.R.C. Markland-N, молодой человек Саймон "Ксенон" Джексон отдыхает, завершив свои работы по проекту быстрее запланированного (впрочем как всегда). Так как свободного времени достаточно много, он надевает свой легендарный хакерский "X" инстинкт и бежит сражаться против банд кибермира.</p><p>Его целью является сеть из $$$n$$$ небольших банд. Их сеть состоит из ровно $$$n - 1$$$ прямых соединений, каждое из которых связывает какие-то две банды вместе. Соединения устроены таким образом, что любые две банды соединены через последовательность прямых соединений.</p><p>Изучая данные, Ксенон понял, что банды используют для самозащиты следующую форму шифрования. Каждому соединению назначено целое число от $$$0$$$ до $$$n - 2$$$, таким образом, что все назначенные числа различны, а каждое число назначено какому-то соединению. Если атакующий пытается получить доступ к защищённым данным, то ему придётся прорваться через $$$S$$$ слоёв с паролями, где $$$S$$$ определяется как:</p><p>$$$$$$S = \sum_{1 \leq u &lt; v \leq n} mex(u, v)$$$$$$</p><p>Здесь $$$mex(u, v)$$$ обозначает наименьшее неотрицательное целое число, которое не встречается на соединениях на единственном простом пути между бандами $$$u$$$ и $$$v$$$.</p><p>Ксенон не знает каким образом числа были назначены соединениям, но это не проблема. Он собирается поручить своим AI перебрать и взломать все пароли, но перед этим он хочет знать чему равно наибольшее возможное значение $$$S$$$, чтобы настроить AI наиболее эффективно.</p><p>Сейчас Ксенон ушёл писать скрипты для AI, и он собирается их закончить в течение двух часов. Не могли бы вы найти наибольшее значение $$$S$$$ перед тем, как он вернётся?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \leq n \leq 3000$$$) — количество банд в сети.</p><p>Каждая из следующих $$$n - 1$$$ строк содержит числа $$$u_i$$$ и $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$; $$$u_i \neq v_i$$$), обозначающие прямое соединение между бандами $$$u_i$$$ и $$$v_i$$$.</p><p>Гарантируется, что связи расположены таким образом, что каждая пара банд соединена ровно одним простым путём.</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> 3 1 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 1 3 1 4 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно достичь максимального $$$S$$$ следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/421d2b1ce0e02f683a77f84bb33a92ce5968e710.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В этой сети, $$$mex(1, 2) = 0$$$, $$$mex(1, 3) = 2$$$ и $$$mex(2, 3) = 1$$$. Таким образом, $$$S = 0 + 2 + 1 = 3$$$.</p><p>Во втором примере можно достичь максимального $$$S$$$ таким образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fa27194eb402038a92a3b9fb5077487aac71d934.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В этой сети все ненулевые значения mex перечислены ниже: </p><ul> <li> $$$mex(1, 3) = 1$$$ </li><li> $$$mex(1, 5) = 2$$$ </li><li> $$$mex(2, 3) = 1$$$ </li><li> $$$mex(2, 5) = 2$$$ </li><li> $$$mex(3, 4) = 1$$$ </li><li> $$$mex(4, 5) = 3$$$ </li></ul><p>Таким образом, $$$S = 1 + 2 + 1 + 2 + 1 + 3 = 10$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="0b7cafdcb5c5b34c8a79a7f5cc42ba01"/> <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="f41d2ac68ef00d0c5fdf5706d652ecfeab2320ff"/> <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='0b7cafdcb5c5b34c8a79a7f5cc42ba01'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1292%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='0b7cafdcb5c5b34c8a79a7f5cc42ba01'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1292">Codeforces Round 614 (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='0b7cafdcb5c5b34c8a79a7f5cc42ba01'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1292/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='0b7cafdcb5c5b34c8a79a7f5cc42ba01'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="519778"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0b7cafdcb5c5b34c8a79a7f5cc42ba01'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="519778"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69012" title="Codeforces Round #614" target="_blank">Codeforces Round #614 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10302" resourceName="Codeforces Round #614" resourceManual="true" src="//codeforces.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/73051" title="Codeforces Round #614 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10313" resourceName="Codeforces Round #614 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/1292">Задачи</a></li> <li><a href="/contest/1292/submit">Отослать</a></li> <li><a href="/contest/1292/my">Мои посылки</a></li> <li><a href="/contest/1292/status">Статус</a></li> <li><a href="/contest/1292/hacks">Взломы</a></li> <li><a href="/contest/1292/room/1">Комната</a></li> <li><a href="/contest/1292/standings">Положение</a></li> <li><a href="/contest/1292/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_bf15b711b152331c821064a341f085a65fe6af8a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>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><div class="epigraph"><div class="epigraph-text"><a href="https://www.youtube.com/watch?v=kwsciXm_7sA"><span class="tex-font-style-it">INSPION FullBand Master - INSPION</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://www.youtube.com/watch?v=kwsciXm_7sA"><span class="tex-font-style-it">INSPION - IOLITE-SUNSTONE</span></a></div></div><p>На другом этаже A.R.C. Markland-N, молодой человек Саймон &quot;Ксенон&quot; Джексон отдыхает, завершив свои работы по проекту быстрее запланированного (впрочем как всегда). Так как свободного времени достаточно много, он надевает свой легендарный хакерский &quot;X&quot; инстинкт и бежит сражаться против банд кибермира.</p><p>Его целью является сеть из $$$n$$$ небольших банд. Их сеть состоит из ровно $$$n - 1$$$ прямых соединений, каждое из которых связывает какие-то две банды вместе. Соединения устроены таким образом, что любые две банды соединены через последовательность прямых соединений.</p><p>Изучая данные, Ксенон понял, что банды используют для самозащиты следующую форму шифрования. Каждому соединению назначено целое число от $$$0$$$ до $$$n - 2$$$, таким образом, что все назначенные числа различны, а каждое число назначено какому-то соединению. Если атакующий пытается получить доступ к защищённым данным, то ему придётся прорваться через $$$S$$$ слоёв с паролями, где $$$S$$$ определяется как:</p><p>$$$$$$S = \sum_{1 \leq u &lt; v \leq n} mex(u, v)$$$$$$</p><p>Здесь $$$mex(u, v)$$$ обозначает наименьшее неотрицательное целое число, которое не встречается на соединениях на единственном простом пути между бандами $$$u$$$ и $$$v$$$.</p><p>Ксенон не знает каким образом числа были назначены соединениям, но это не проблема. Он собирается поручить своим AI перебрать и взломать все пароли, но перед этим он хочет знать чему равно наибольшее возможное значение $$$S$$$, чтобы настроить AI наиболее эффективно.</p><p>Сейчас Ксенон ушёл писать скрипты для AI, и он собирается их закончить в течение двух часов. Не могли бы вы найти наибольшее значение $$$S$$$ перед тем, как он вернётся?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \leq n \leq 3000$$$) — количество банд в сети.</p><p>Каждая из следующих $$$n - 1$$$ строк содержит числа $$$u_i$$$ и $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$; $$$u_i \neq v_i$$$), обозначающие прямое соединение между бандами $$$u_i$$$ и $$$v_i$$$.</p><p>Гарантируется, что связи расположены таким образом, что каждая пара банд соединена ровно одним простым путём.</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> 3 1 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 1 3 1 4 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно достичь максимального $$$S$$$ следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/421d2b1ce0e02f683a77f84bb33a92ce5968e710.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В этой сети, $$$mex(1, 2) = 0$$$, $$$mex(1, 3) = 2$$$ и $$$mex(2, 3) = 1$$$. Таким образом, $$$S = 0 + 2 + 1 = 3$$$.</p><p>Во втором примере можно достичь максимального $$$S$$$ таким образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fa27194eb402038a92a3b9fb5077487aac71d934.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В этой сети все ненулевые значения mex перечислены ниже: </p><ul> <li> $$$mex(1, 3) = 1$$$ </li><li> $$$mex(1, 5) = 2$$$ </li><li> $$$mex(2, 3) = 1$$$ </li><li> $$$mex(2, 5) = 2$$$ </li><li> $$$mex(3, 4) = 1$$$ </li><li> $$$mex(4, 5) = 3$$$ </li></ul><p>Таким образом, $$$S = 1 + 2 + 1 + 2 + 1 + 3 = 10$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:55: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:'812494a29e9c9d3a',t:'MTY5NjY2NTMxMy43ODYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2300"]
1292D
1292
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><div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/aesir-chaos"><span class="tex-font-style-it">Æsir - CHAOS</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/aesir-v"><span class="tex-font-style-it">Æsir - V.</span></a></div></div><p><span class="tex-font-style-it">«Всё было спланировано, Никаких больше скрытых забот. Состояние Цитуса тоже совершенно..»</span></p><p><span class="tex-font-style-it">Текущее время...... 00:01:12......</span></p><p><span class="tex-font-style-it">Время пришло.</span></p><p>Образцов эмоций теперь достаточно. Прошло почти три года, и пришло время для Айви разбудить свою связанную сестру Ванессу.</p><p>Система внутри библиотеки A.R.C. может быть представлена как неориентированный граф с бесконечным числом обрабатывающих вершин, пронумерованных последовательными положительными целыми числами ($$$1, 2, 3, \ldots$$$). Вершина с номером $$$x$$$ ($$$x &gt; 1$$$) напрямую соединена с вершиной с номером $$$\frac{x}{f(x)}$$$, где $$$f(x)$$$ обозначает наименьший простой делитель $$$x$$$.</p><p>Разум Ванессы разделён на $$$n$$$ фрагментов. Спустя более 500 лет в коме, фрагменты несколько подраскидало: $$$i$$$-й фрагмент теперь находится в вершине с номером $$$k_i!$$$ (факториал $$$k_i$$$).</p><p>Чтобы максимизировать шансы успешного пробуждения, Айви хочет разместить образцы эмоций в вершине $$$P$$$, такой что суммарная длина всех путей от каждого фрагмента до $$$P$$$ является минимально возможной. В случае если несколько фрагментов расположены в одной и той же вершине, путь от них до $$$P$$$ учитывается несколько раз.</p><p>В мире нулей и единиц такое требование вполне тривиально для Айви. Не более, чем секундой позже, она уже нашла такую вершину.</p><p>Возможно ли такое же для простого смертного как вы?</p><p>Для простоты, найдите минимальную суммарную длину путей от каждого фрагмента до оптимальной вершины $$$P$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 10^6$$$) — количество фрагментов в разуме Ванессы.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$k_1, k_2, \ldots, k_n$$$ ($$$0 \le k_i \le 5000$$$), задающие вершины содержащие фрагменты разума Ванессы: $$$i$$$-й фрагмент расположен в вершине $$$k_i!$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, обозначающее минимальную сумму путей от фрагментов до вершины с образцами эмоций $$$P$$$.</p><p>Напомним, что если несколько фрагментов расположены в одной вершины, то расстояние от этой вершины до $$$P$$$ нужно учесть несколько раз.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 4 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первые $$$24$$$ вершины системы выглядят следующим образом (вершины $$$1!$$$, $$$2!$$$, $$$3!$$$, $$$4!$$$ обозначены жирным):</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/043302b7f3870a8689d82fdc00b8b7beb0fada68.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>В первом примере Айви может разместить образцы эмоций в вершине $$$1$$$, тогда:</p><ul> <li> Расстояние от первого фрагмента Ванессы до вершины $$$1$$$ равно $$$1$$$. </li><li> Расстояние от второго фрагмента Ванессы до вершины $$$1$$$ равно $$$0$$$. </li><li> Расстояние от третьего фрагмента Ванессы до вершины $$$1$$$ равно $$$4$$$. </li></ul><p>Суммарная длина равна $$$5$$$.</p><p>Во втором примере Айви оптимальной вершина для сбора является $$$6$$$:</p><ul> <li> Расстояние от первого фрагмента Ванессы до вершины $$$6$$$ равно $$$0$$$. </li><li> Расстояние от второго фрагмента Ванессы до вершины $$$6$$$ равно $$$2$$$.. </li><li> Расстояние от третьего фрагмента Ванессы до вершины $$$6$$$ равно $$$2$$$. </li><li> Расстояние от четвёртого фрагмента Ванессы до вершины $$$6$$$ снова равно $$$2$$$. </li></ul><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="688e8f46182b82067a028fb976c87760"/> <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="f41d2ac68ef00d0c5fdf5706d652ecfeab2320ff"/> <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='688e8f46182b82067a028fb976c87760'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1292%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='688e8f46182b82067a028fb976c87760'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1292">Codeforces Round 614 (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='688e8f46182b82067a028fb976c87760'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1292/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='688e8f46182b82067a028fb976c87760'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="519779"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='688e8f46182b82067a028fb976c87760'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="519779"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69012" title="Codeforces Round #614" target="_blank">Codeforces Round #614 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10302" resourceName="Codeforces Round #614" resourceManual="true" src="//codeforces.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/73051" title="Codeforces Round #614 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10313" resourceName="Codeforces Round #614 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/1292">Задачи</a></li> <li><a href="/contest/1292/submit">Отослать</a></li> <li><a href="/contest/1292/my">Мои посылки</a></li> <li><a href="/contest/1292/status">Статус</a></li> <li><a href="/contest/1292/hacks">Взломы</a></li> <li><a href="/contest/1292/room/1">Комната</a></li> <li><a href="/contest/1292/standings">Положение</a></li> <li><a href="/contest/1292/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_453580b2f25a33cf336d8c68f838056f79bf7cef"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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><div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/aesir-chaos"><span class="tex-font-style-it">Æsir - CHAOS</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/aesir-v"><span class="tex-font-style-it">Æsir - V.</span></a></div></div><p><span class="tex-font-style-it">«Всё было спланировано, Никаких больше скрытых забот. Состояние Цитуса тоже совершенно..»</span></p><p><span class="tex-font-style-it">Текущее время...... 00:01:12......</span></p><p><span class="tex-font-style-it">Время пришло.</span></p><p>Образцов эмоций теперь достаточно. Прошло почти три года, и пришло время для Айви разбудить свою связанную сестру Ванессу.</p><p>Система внутри библиотеки A.R.C. может быть представлена как неориентированный граф с бесконечным числом обрабатывающих вершин, пронумерованных последовательными положительными целыми числами ($$$1, 2, 3, \ldots$$$). Вершина с номером $$$x$$$ ($$$x &gt; 1$$$) напрямую соединена с вершиной с номером $$$\frac{x}{f(x)}$$$, где $$$f(x)$$$ обозначает наименьший простой делитель $$$x$$$.</p><p>Разум Ванессы разделён на $$$n$$$ фрагментов. Спустя более 500 лет в коме, фрагменты несколько подраскидало: $$$i$$$-й фрагмент теперь находится в вершине с номером $$$k_i!$$$ (факториал $$$k_i$$$).</p><p>Чтобы максимизировать шансы успешного пробуждения, Айви хочет разместить образцы эмоций в вершине $$$P$$$, такой что суммарная длина всех путей от каждого фрагмента до $$$P$$$ является минимально возможной. В случае если несколько фрагментов расположены в одной и той же вершине, путь от них до $$$P$$$ учитывается несколько раз.</p><p>В мире нулей и единиц такое требование вполне тривиально для Айви. Не более, чем секундой позже, она уже нашла такую вершину.</p><p>Возможно ли такое же для простого смертного как вы?</p><p>Для простоты, найдите минимальную суммарную длину путей от каждого фрагмента до оптимальной вершины $$$P$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 10^6$$$) — количество фрагментов в разуме Ванессы.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$k_1, k_2, \ldots, k_n$$$ ($$$0 \le k_i \le 5000$$$), задающие вершины содержащие фрагменты разума Ванессы: $$$i$$$-й фрагмент расположен в вершине $$$k_i!$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, обозначающее минимальную сумму путей от фрагментов до вершины с образцами эмоций $$$P$$$.</p><p>Напомним, что если несколько фрагментов расположены в одной вершины, то расстояние от этой вершины до $$$P$$$ нужно учесть несколько раз.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 4 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первые $$$24$$$ вершины системы выглядят следующим образом (вершины $$$1!$$$, $$$2!$$$, $$$3!$$$, $$$4!$$$ обозначены жирным):</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/043302b7f3870a8689d82fdc00b8b7beb0fada68.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>В первом примере Айви может разместить образцы эмоций в вершине $$$1$$$, тогда:</p><ul> <li> Расстояние от первого фрагмента Ванессы до вершины $$$1$$$ равно $$$1$$$. </li><li> Расстояние от второго фрагмента Ванессы до вершины $$$1$$$ равно $$$0$$$. </li><li> Расстояние от третьего фрагмента Ванессы до вершины $$$1$$$ равно $$$4$$$. </li></ul><p>Суммарная длина равна $$$5$$$.</p><p>Во втором примере Айви оптимальной вершина для сбора является $$$6$$$:</p><ul> <li> Расстояние от первого фрагмента Ванессы до вершины $$$6$$$ равно $$$0$$$. </li><li> Расстояние от второго фрагмента Ванессы до вершины $$$6$$$ равно $$$2$$$.. </li><li> Расстояние от третьего фрагмента Ванессы до вершины $$$6$$$ равно $$$2$$$. </li><li> Расстояние от четвёртого фрагмента Ванессы до вершины $$$6$$$ снова равно $$$2$$$. </li></ul><p>Суммарная длина равна $$$6$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:55: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:'812494ab0c6c1693',t:'MTY5NjY2NTMxNS4yMjgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2700"]
1292E
1292
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><div class="epigraph"><div class="epigraph-text"><a href="https://www.youtube.com/watch?v=5VleIdkEeak"><span class="tex-font-style-it">MisoilePunch♪ - 彩</span></a></div></div><p><span class="tex-font-style-it">Это интерактивная задача!</span></p><p>Это был обычный день в тайном офисе в A.R.C. Markland-N, когда капитан-исследователь Сагар передал Рин необычный артефакт.</p><p>После некоторого анализа, Рин поняла, что этот артефакт содержит информацию о странном цветке, который существовал задолго до нашей эры. Однако информация о химической структуре цветка оказалась зашифрованной.</p><p>Химическая структура цветка может быть представлена как строка $$$p$$$. Исходя из незашифрованных бумаг рядом, Рин выяснила, длину строки $$$n$$$ и что эта строка может содержать только следующие три буквы: «<span class="tex-font-style-tt">C</span>» (углерод), «<span class="tex-font-style-tt">H</span>» (водород), и «<span class="tex-font-style-tt">O</span>» (кислород).</p><p>В каждый момент Рин может ввести строку $$$s$$$ произвольной длины в специальный терминал артефакт, и он в ответ выведет все возможные начальные позиции вхождения $$$s$$$ как <span class="tex-font-style-it">подстроки</span> в $$$p$$$.</p><p>Тем не менее, запас энергии артефакта достаточно ограничен, и артефакт нельзя перезарядить, так как его технология слишком несовременная и несовместима ни с одним устройством A.R.C. Более точно:</p><ul> <li> Артефакт содержит $$$\frac{7}{5}$$$ единиц энергии. </li><li> Каждый раз, когда Рин вводит строку $$$s$$$ длины $$$t$$$, артефакт тратит $$$\frac{1}{t^2}$$$ единиц энергии. </li><li> Если уровень энергии достигнет нуля, то задание будет считаться проваленным, а артефакт навсегда затемнится. </li></ul><p>Артефакт очень ценен, но и столь же хрупок. Рин очень боится повредить артефакт навсегда в попытках извлечь данные. Не могли бы вы ей помочь?</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Взаимодействие начинается с целого числа $$$t$$$ ($$$1 \le t \le 500$$$), количества тестовых случаев. Взаимодействие для каждого тестового случая описано ниже:</p><p>Сначала вам нужно считать целое число $$$n$$$ ($$$4 \le n \le 50$$$), длину строки $$$p$$$.</p><p>После этого вы можете делать запросы вида «<span class="tex-font-style-tt">? s</span>» ($$$1 \le |s| \le n$$$), чтобы найти вхождения $$$s$$$ в $$$p$$$.</p><p>После запроса, вам нужно считать ответ на него как последовательность целых чисел в одной строке:</p><ul><li> Первое число $$$k$$$ обозначает количество вхождений $$$s$$$ как подстроку в $$$p$$$ ($$$-1 \le k \le n$$$). Если $$$k = -1$$$, то это означает, что вы превысили ограничение на энергию или сделали некорректный запрос, в этом случае вам нужно немедленно завершить программу, чтобы гарантировать вердикт «<span class="tex-font-style-tt">Неправильный ответ</span>». В противном случае вердикт может оказаться любым, так как ваше решение продолжит чтение из закрытого потока.</li><li> Следующие $$$k$$$ целых чисел $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_1 &lt; a_2 &lt; \ldots &lt; a_k \le n$$$) обозначают начальные позиции подстрок равных строке $$$s$$$ .</li></ul><p>Когда вы выясните строку $$$p$$$ выведите «<span class="tex-font-style-tt">! $$$p$$$</span>» чтобы завершить текущий тестовый случай. Это действие не тратит энергию. Интерактор в ответ вернёт $$$1$$$ или $$$0$$$. Если интерактор вернул $$$1$$$, то вы можете начать обрабатывать следующий тестовый случай, если он есть, или завершить программу, если это был последний тестовый случай.</p><p>Если интерактор вернул $$$0$$$, то это означает что ваше предположение некорректно и вы должны немедленно завершить программу, чтобы гарантировать вердикт «<span class="tex-font-style-tt">Неправильный ответ</span>».</p><p>Обратите внимание что в каждом тестовом случае строка $$$p$$$ зафиксирована заранее и не меняется в зависимости от запросов, иначе говоря, интерактор не адаптивен.</p><p>После вывода любого запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы можете получить вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul><li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++;</li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java;</li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal;</li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python;</li><li> смотрите документацию для других языков.</li></ul><p><span class="tex-font-style-bf">Взломы</span></p><p>Для взломов используйте следующий формат:</p><p>Первая строка должна содержать целое число $$$t$$$ ($$$t = 1$$$).</p><p>Вторая строка строка должна содержит целое число $$$n$$$ ($$$4 \le n \le 50$$$) — длину строки.</p><p>Вторая строка должна содержать строку длины $$$n$$$, состоящую только из символов «<span class="tex-font-style-tt">C</span>», «<span class="tex-font-style-tt">H</span>» и «<span class="tex-font-style-tt">O</span>». Эта та строка, которую взламываемому решению придётся угадать.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 4 2 1 2 1 2 0 1</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? C ? CH ? CCHO ! CCHH </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 5 0 2 2 3 1 8 1 5 1 5 1 3 2 1 2 1</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? O ? HHH ! CHHHH ? COO ? COOH ? HCCOO ? HH ! HHHCCOOH </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обратите внимание что в примере взаимодействия есть лишние пустые строки для удобства чтения.</p><p>В реальном взаимодействия таких строк нет, и ваша программа тоже не должна их выводить.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="27ddfaaf4cbacdb3b4f264b20e19e92f"/> <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="f41d2ac68ef00d0c5fdf5706d652ecfeab2320ff"/> <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='27ddfaaf4cbacdb3b4f264b20e19e92f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1292%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='27ddfaaf4cbacdb3b4f264b20e19e92f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1292">Codeforces Round 614 (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='27ddfaaf4cbacdb3b4f264b20e19e92f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1292/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='27ddfaaf4cbacdb3b4f264b20e19e92f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="519780"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='27ddfaaf4cbacdb3b4f264b20e19e92f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="519780"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69012" title="Codeforces Round #614" target="_blank">Codeforces Round #614 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10302" resourceName="Codeforces Round #614" resourceManual="true" src="//codeforces.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/73051" title="Codeforces Round #614 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10313" resourceName="Codeforces Round #614 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/1292">Задачи</a></li> <li><a href="/contest/1292/submit">Отослать</a></li> <li><a href="/contest/1292/my">Мои посылки</a></li> <li><a href="/contest/1292/status">Статус</a></li> <li><a href="/contest/1292/hacks">Взломы</a></li> <li><a href="/contest/1292/room/1">Комната</a></li> <li><a href="/contest/1292/standings">Положение</a></li> <li><a href="/contest/1292/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b329dfaf7019b8e1142cfd182656b6dab9e1cc3f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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><div class="epigraph"><div class="epigraph-text"><a href="https://www.youtube.com/watch?v=5VleIdkEeak"><span class="tex-font-style-it">MisoilePunch♪ - 彩</span></a></div></div><p><span class="tex-font-style-it">Это интерактивная задача!</span></p><p>Это был обычный день в тайном офисе в A.R.C. Markland-N, когда капитан-исследователь Сагар передал Рин необычный артефакт.</p><p>После некоторого анализа, Рин поняла, что этот артефакт содержит информацию о странном цветке, который существовал задолго до нашей эры. Однако информация о химической структуре цветка оказалась зашифрованной.</p><p>Химическая структура цветка может быть представлена как строка $$$p$$$. Исходя из незашифрованных бумаг рядом, Рин выяснила, длину строки $$$n$$$ и что эта строка может содержать только следующие три буквы: «<span class="tex-font-style-tt">C</span>» (углерод), «<span class="tex-font-style-tt">H</span>» (водород), и «<span class="tex-font-style-tt">O</span>» (кислород).</p><p>В каждый момент Рин может ввести строку $$$s$$$ произвольной длины в специальный терминал артефакт, и он в ответ выведет все возможные начальные позиции вхождения $$$s$$$ как <span class="tex-font-style-it">подстроки</span> в $$$p$$$.</p><p>Тем не менее, запас энергии артефакта достаточно ограничен, и артефакт нельзя перезарядить, так как его технология слишком несовременная и несовместима ни с одним устройством A.R.C. Более точно:</p><ul> <li> Артефакт содержит $$$\frac{7}{5}$$$ единиц энергии. </li><li> Каждый раз, когда Рин вводит строку $$$s$$$ длины $$$t$$$, артефакт тратит $$$\frac{1}{t^2}$$$ единиц энергии. </li><li> Если уровень энергии достигнет нуля, то задание будет считаться проваленным, а артефакт навсегда затемнится. </li></ul><p>Артефакт очень ценен, но и столь же хрупок. Рин очень боится повредить артефакт навсегда в попытках извлечь данные. Не могли бы вы ей помочь?</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Взаимодействие начинается с целого числа $$$t$$$ ($$$1 \le t \le 500$$$), количества тестовых случаев. Взаимодействие для каждого тестового случая описано ниже:</p><p>Сначала вам нужно считать целое число $$$n$$$ ($$$4 \le n \le 50$$$), длину строки $$$p$$$.</p><p>После этого вы можете делать запросы вида «<span class="tex-font-style-tt">? s</span>» ($$$1 \le |s| \le n$$$), чтобы найти вхождения $$$s$$$ в $$$p$$$.</p><p>После запроса, вам нужно считать ответ на него как последовательность целых чисел в одной строке:</p><ul><li> Первое число $$$k$$$ обозначает количество вхождений $$$s$$$ как подстроку в $$$p$$$ ($$$-1 \le k \le n$$$). Если $$$k = -1$$$, то это означает, что вы превысили ограничение на энергию или сделали некорректный запрос, в этом случае вам нужно немедленно завершить программу, чтобы гарантировать вердикт «<span class="tex-font-style-tt">Неправильный ответ</span>». В противном случае вердикт может оказаться любым, так как ваше решение продолжит чтение из закрытого потока.</li><li> Следующие $$$k$$$ целых чисел $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_1 &lt; a_2 &lt; \ldots &lt; a_k \le n$$$) обозначают начальные позиции подстрок равных строке $$$s$$$ .</li></ul><p>Когда вы выясните строку $$$p$$$ выведите «<span class="tex-font-style-tt">! $$$p$$$</span>» чтобы завершить текущий тестовый случай. Это действие не тратит энергию. Интерактор в ответ вернёт $$$1$$$ или $$$0$$$. Если интерактор вернул $$$1$$$, то вы можете начать обрабатывать следующий тестовый случай, если он есть, или завершить программу, если это был последний тестовый случай.</p><p>Если интерактор вернул $$$0$$$, то это означает что ваше предположение некорректно и вы должны немедленно завершить программу, чтобы гарантировать вердикт «<span class="tex-font-style-tt">Неправильный ответ</span>».</p><p>Обратите внимание что в каждом тестовом случае строка $$$p$$$ зафиксирована заранее и не меняется в зависимости от запросов, иначе говоря, интерактор не адаптивен.</p><p>После вывода любого запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы можете получить вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul><li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++;</li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java;</li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal;</li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python;</li><li> смотрите документацию для других языков.</li></ul><p><span class="tex-font-style-bf">Взломы</span></p><p>Для взломов используйте следующий формат:</p><p>Первая строка должна содержать целое число $$$t$$$ ($$$t = 1$$$).</p><p>Вторая строка строка должна содержит целое число $$$n$$$ ($$$4 \le n \le 50$$$) — длину строки.</p><p>Вторая строка должна содержать строку длины $$$n$$$, состоящую только из символов «<span class="tex-font-style-tt">C</span>», «<span class="tex-font-style-tt">H</span>» и «<span class="tex-font-style-tt">O</span>». Эта та строка, которую взламываемому решению придётся угадать.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 4 2 1 2 1 2 0 1</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? C ? CH ? CCHO ! CCHH </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 5 0 2 2 3 1 8 1 5 1 5 1 3 2 1 2 1</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? O ? HHH ! CHHHH ? COO ? COOH ? HCCOO ? HH ! HHHCCOOH </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обратите внимание что в примере взаимодействия есть лишние пустые строки для удобства чтения.</p><p>В реальном взаимодействия таких строк нет, и ваша программа тоже не должна их выводить.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=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:55: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:'812494b3ecbd163d',t:'MTY5NjY2NTMxNi44OTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*3500"]
1292F
1292
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><div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/hanatsuka/sihanatsuka-ember"><span class="tex-font-style-it">SIHanatsuka - EMber</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/hanatsuka/sihanatsuka-atonement"><span class="tex-font-style-it">SIHanatsuka - ATONEMENT</span></a></div></div><p>Давным давно, семилетняя Нора любила играть в игрушки вместе со своим созданием ROBO_Head-02, не только для того чтобы развлечься, но и чтобы улучшить его способности.</p><p>Однажды, приёмный отец Норы, Феникс Уайл, принёс Норе $$$n$$$ коробок с игрушками. Перед тем как их распаковать, Нора решила устроить для ROBO небольшую игру.</p><p>Она пронумеровала все $$$n$$$ коробок используя $$$n$$$ различных целых чисел $$$a_1, a_2, \ldots, a_n$$$ и попросила ROBO выполнить ноль или более операций следующего вида:</p><ul> <li> Выбрать три различных индекса $$$i$$$, $$$j$$$ и $$$k$$$, таких что $$$a_i \mid a_j$$$ и $$$a_i \mid a_k$$$. Иными словами, $$$a_i$$$ делит и $$$a_j$$$, и $$$a_k$$$. Иначе говоря, $$$a_j \bmod a_i = 0$$$, $$$a_k \bmod a_i = 0$$$.</li><li> Затем, Нора передаст $$$k$$$-ю коробку ROBO, а тот положит её наверх стопки с коробками рядом с ним. Изначально эта стопка пуста. </li><li> После этого коробка $$$k$$$ становится недоступной для любых дальнейших действий. </li></ul><p>После девяти игр, это процесс весьма позабавил Нору. Она попросила ROBO посчитать количество возможных стопок с коробками, имеющие <span class="tex-font-style-bf">максимально</span> возможный размер, которые могут получиться. Две стопки считаются различными, если существует хотя бы одна позиция, в которой они отличаются.</p><p>Так как ROBO пока на очень ранней стадии развития, да и Нора достаточно молода, чтобы концентрироваться надолго, они оба заснули, не найдя ответа. Не могли бы вы им помочь?</p><p>Так как количество таких стопок может быть достаточно большим, выведите его по модулю $$$10^9 + 7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$3 \le n \le 60$$$) — количество коробок.</p><p>Вторая строка содержит $$$n$$$ различных целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 60$$$), где $$$a_i$$$ обозначает пометку на $$$i$$$-й коробке.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите количество различных максимальных по размеру стопок, которые могли получится у ROBO, по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 6 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 3 4 9 12 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 5 7 2 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обозначим содержимое стопки как последовательность $$$b$$$, где самая нижняя коробка стопки находится на самой левой позиции.</p><p>В первом примере возможно $$$2$$$ различных стопки: </p><ul> <li> $$$b = [6]$$$ ($$$[2, \mathbf{6}, 8] \xrightarrow{(1, 3, 2)} [2, 8]$$$) </li><li> $$$b = [8]$$$ ($$$[2, 6, \mathbf{8}] \xrightarrow{(1, 2, 3)} [2, 6]$$$) </li></ul><p>Во втором примере возможно $$$4$$$ различных стопки: </p><ul> <li> $$$b = [9, 12]$$$ ($$$[2, 3, 4, \mathbf{9}, 12] \xrightarrow{(2, 5, 4)} [2, 3, 4, \mathbf{12}] \xrightarrow{(1, 3, 4)} [2, 3, 4]$$$) </li><li> $$$b = [4, 12]$$$ ($$$[2, 3, \mathbf{4}, 9, 12] \xrightarrow{(1, 5, 3)} [2, 3, 9, \mathbf{12}] \xrightarrow{(2, 3, 4)} [2, 3, 9]$$$) </li><li> $$$b = [4, 9]$$$ ($$$[2, 3, \mathbf{4}, 9, 12] \xrightarrow{(1, 5, 3)} [2, 3, \mathbf{9}, 12] \xrightarrow{(2, 4, 3)} [2, 3, 12]$$$) </li><li> $$$b = [9, 4]$$$ ($$$[2, 3, 4, \mathbf{9}, 12] \xrightarrow{(2, 5, 4)} [2, 3, \mathbf{4}, 12] \xrightarrow{(1, 4, 3)} [2, 3, 12]$$$) </li></ul><p>В третьем примере ROBO не сможет сделать ничего. Поэтому возможна только $$$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="6e906f376eda895bcb28902620714ff8"/> <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="f41d2ac68ef00d0c5fdf5706d652ecfeab2320ff"/> <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='6e906f376eda895bcb28902620714ff8'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1292%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='6e906f376eda895bcb28902620714ff8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1292">Codeforces Round 614 (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='6e906f376eda895bcb28902620714ff8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1292/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound 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='6e906f376eda895bcb28902620714ff8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="519781"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6e906f376eda895bcb28902620714ff8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="519781"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69012" title="Codeforces Round #614" target="_blank">Codeforces Round #614 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10302" resourceName="Codeforces Round #614" resourceManual="true" src="//codeforces.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/73051" title="Codeforces Round #614 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10313" resourceName="Codeforces Round #614 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/1292">Задачи</a></li> <li><a href="/contest/1292/submit">Отослать</a></li> <li><a href="/contest/1292/my">Мои посылки</a></li> <li><a href="/contest/1292/status">Статус</a></li> <li><a href="/contest/1292/hacks">Взломы</a></li> <li><a href="/contest/1292/room/1">Комната</a></li> <li><a href="/contest/1292/standings">Положение</a></li> <li><a href="/contest/1292/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0beec2a68d5656ffc98fdfd509a2b45153f074af"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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><div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/hanatsuka/sihanatsuka-ember"><span class="tex-font-style-it">SIHanatsuka - EMber</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/hanatsuka/sihanatsuka-atonement"><span class="tex-font-style-it">SIHanatsuka - ATONEMENT</span></a></div></div><p>Давным давно, семилетняя Нора любила играть в игрушки вместе со своим созданием ROBO_Head-02, не только для того чтобы развлечься, но и чтобы улучшить его способности.</p><p>Однажды, приёмный отец Норы, Феникс Уайл, принёс Норе $$$n$$$ коробок с игрушками. Перед тем как их распаковать, Нора решила устроить для ROBO небольшую игру.</p><p>Она пронумеровала все $$$n$$$ коробок используя $$$n$$$ различных целых чисел $$$a_1, a_2, \ldots, a_n$$$ и попросила ROBO выполнить ноль или более операций следующего вида:</p><ul> <li> Выбрать три различных индекса $$$i$$$, $$$j$$$ и $$$k$$$, таких что $$$a_i \mid a_j$$$ и $$$a_i \mid a_k$$$. Иными словами, $$$a_i$$$ делит и $$$a_j$$$, и $$$a_k$$$. Иначе говоря, $$$a_j \bmod a_i = 0$$$, $$$a_k \bmod a_i = 0$$$.</li><li> Затем, Нора передаст $$$k$$$-ю коробку ROBO, а тот положит её наверх стопки с коробками рядом с ним. Изначально эта стопка пуста. </li><li> После этого коробка $$$k$$$ становится недоступной для любых дальнейших действий. </li></ul><p>После девяти игр, это процесс весьма позабавил Нору. Она попросила ROBO посчитать количество возможных стопок с коробками, имеющие <span class="tex-font-style-bf">максимально</span> возможный размер, которые могут получиться. Две стопки считаются различными, если существует хотя бы одна позиция, в которой они отличаются.</p><p>Так как ROBO пока на очень ранней стадии развития, да и Нора достаточно молода, чтобы концентрироваться надолго, они оба заснули, не найдя ответа. Не могли бы вы им помочь?</p><p>Так как количество таких стопок может быть достаточно большим, выведите его по модулю $$$10^9 + 7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$3 \le n \le 60$$$) — количество коробок.</p><p>Вторая строка содержит $$$n$$$ различных целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 60$$$), где $$$a_i$$$ обозначает пометку на $$$i$$$-й коробке.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите количество различных максимальных по размеру стопок, которые могли получится у ROBO, по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 6 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 3 4 9 12 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 5 7 2 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обозначим содержимое стопки как последовательность $$$b$$$, где самая нижняя коробка стопки находится на самой левой позиции.</p><p>В первом примере возможно $$$2$$$ различных стопки: </p><ul> <li> $$$b = [6]$$$ ($$$[2, \mathbf{6}, 8] \xrightarrow{(1, 3, 2)} [2, 8]$$$) </li><li> $$$b = [8]$$$ ($$$[2, 6, \mathbf{8}] \xrightarrow{(1, 2, 3)} [2, 6]$$$) </li></ul><p>Во втором примере возможно $$$4$$$ различных стопки: </p><ul> <li> $$$b = [9, 12]$$$ ($$$[2, 3, 4, \mathbf{9}, 12] \xrightarrow{(2, 5, 4)} [2, 3, 4, \mathbf{12}] \xrightarrow{(1, 3, 4)} [2, 3, 4]$$$) </li><li> $$$b = [4, 12]$$$ ($$$[2, 3, \mathbf{4}, 9, 12] \xrightarrow{(1, 5, 3)} [2, 3, 9, \mathbf{12}] \xrightarrow{(2, 3, 4)} [2, 3, 9]$$$) </li><li> $$$b = [4, 9]$$$ ($$$[2, 3, \mathbf{4}, 9, 12] \xrightarrow{(1, 5, 3)} [2, 3, \mathbf{9}, 12] \xrightarrow{(2, 4, 3)} [2, 3, 12]$$$) </li><li> $$$b = [9, 4]$$$ ($$$[2, 3, 4, \mathbf{9}, 12] \xrightarrow{(2, 5, 4)} [2, 3, \mathbf{4}, 12] \xrightarrow{(1, 4, 3)} [2, 3, 12]$$$) </li></ul><p>В третьем примере ROBO не сможет сделать ничего. Поэтому возможна только $$$1$$$ стопка, и это пустая стопка.</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:55: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:'812494be598375b7',t:'MTY5NjY2NTMxOC4zNDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "*3500"]
1293A
1293
A
ru
A. КоннеР и A.R.C. Markland-N
<div class="problem-statement"><div class="header"><div class="title">A. КоннеР и A.R.C. Markland-N</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><div class="epigraph"><div class="epigraph-text"><a href="https://www.youtube.com/watch?v=55Ca6av1kAY"><span class="tex-font-style-it">Sakuzyo - Imprinting</span></a></div></div><p>A.R.C. Markland-N это высокое $$$n$$$-этажное здание с этажами, пронумерованными от $$$1$$$ до $$$n$$$. Между любыми двумя соседними этажами есть лестница их соединяющая.</p><p>У нашего сенсея Колина «КоннеР» Неймена Jr приближается время обеда, поэтому он решил выбрать, в каком месте он собирается поесть.</p><p>Офис Коннера располагается на $$$s$$$-м этаже здания. На каждом этаже здания расположено по одному ресторану, в том числе на этаже $$$s$$$. Однако в связи с идущей реконструкцией, $$$k$$$ ресторанов сейчас закрыты.</p><p>Коннер не хочет терять много времени на еду, поэтому хочет найти открытый ресторан как можно ближе к нему. Иначе говоря, его интересует ресторан, требующий прохода по минимальному количеству лестниц от этажа Коннера.</p><p>Помогите Коннеру, и кто знает, может быть вы заслужите его похвалу и даже сможете насладиться обедом вместе с ним в элегантном стиле Нейманов!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора содержит целые числа $$$n$$$, $$$s$$$ и $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — количество этажей в A.R.C. Markland-N, этаж на котором работает Коннер и количество закрытых ресторанов.</p><p>Вторая строка каждого набора содержит $$$k$$$ различных целых чисел $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — этажи, на которых расположены закрытые рестораны.</p><p>Гарантируется, что сумма значений $$$k$$$ по всем наборам во входных данных не превосходит $$$1000$$$.</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 5 2 3 1 2 3 4 3 3 4 1 2 10 2 6 1 2 3 4 5 7 2 1 1 2 100 76 8 76 75 36 67 41 74 10 77 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 4 0 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных примера ближайший открытый ресторан расположен на $$$4$$$-м этаже.</p><p>Во втором наборе входных данных примера ресторан на этаже с офисом Коннера не закрыт, так что Коннер сможет пообедать там.</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="0d40ca95d10282af6def65dd23f22972"/> <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="f1f290e5f7b278d65660c115fd3c740ff743f745"/> <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='0d40ca95d10282af6def65dd23f22972'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1293%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='0d40ca95d10282af6def65dd23f22972'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1293">Codeforces Round 614 (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='0d40ca95d10282af6def65dd23f22972'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1293/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='0d40ca95d10282af6def65dd23f22972'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="519782"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0d40ca95d10282af6def65dd23f22972'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="519782"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69012" title="Codeforces Round #614" target="_blank">Codeforces Round #614 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10303" resourceName="Codeforces Round #614" resourceManual="true" src="//codeforces.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/73051" title="Codeforces Round #614 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10314" resourceName="Codeforces Round #614 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/1293">Задачи</a></li> <li><a href="/contest/1293/submit">Отослать</a></li> <li><a href="/contest/1293/my">Мои посылки</a></li> <li><a href="/contest/1293/status">Статус</a></li> <li><a href="/contest/1293/hacks">Взломы</a></li> <li><a href="/contest/1293/room/1">Комната</a></li> <li><a href="/contest/1293/standings">Положение</a></li> <li><a href="/contest/1293/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c6c4c6f4e97f3de182a72885860a750361ba51ea"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. КоннеР и A.R.C. Markland-N</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><div class="epigraph"><div class="epigraph-text"><a href="https://www.youtube.com/watch?v=55Ca6av1kAY"><span class="tex-font-style-it">Sakuzyo - Imprinting</span></a></div></div><p>A.R.C. Markland-N это высокое $$$n$$$-этажное здание с этажами, пронумерованными от $$$1$$$ до $$$n$$$. Между любыми двумя соседними этажами есть лестница их соединяющая.</p><p>У нашего сенсея Колина «КоннеР» Неймена Jr приближается время обеда, поэтому он решил выбрать, в каком месте он собирается поесть.</p><p>Офис Коннера располагается на $$$s$$$-м этаже здания. На каждом этаже здания расположено по одному ресторану, в том числе на этаже $$$s$$$. Однако в связи с идущей реконструкцией, $$$k$$$ ресторанов сейчас закрыты.</p><p>Коннер не хочет терять много времени на еду, поэтому хочет найти открытый ресторан как можно ближе к нему. Иначе говоря, его интересует ресторан, требующий прохода по минимальному количеству лестниц от этажа Коннера.</p><p>Помогите Коннеру, и кто знает, может быть вы заслужите его похвалу и даже сможете насладиться обедом вместе с ним в элегантном стиле Нейманов!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора содержит целые числа $$$n$$$, $$$s$$$ и $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — количество этажей в A.R.C. Markland-N, этаж на котором работает Коннер и количество закрытых ресторанов.</p><p>Вторая строка каждого набора содержит $$$k$$$ различных целых чисел $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — этажи, на которых расположены закрытые рестораны.</p><p>Гарантируется, что сумма значений $$$k$$$ по всем наборам во входных данных не превосходит $$$1000$$$.</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 5 2 3 1 2 3 4 3 3 4 1 2 10 2 6 1 2 3 4 5 7 2 1 1 2 100 76 8 76 75 36 67 41 74 10 77 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 4 0 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных примера ближайший открытый ресторан расположен на $$$4$$$-м этаже.</p><p>Во втором наборе входных данных примера ресторан на этаже с офисом Коннера не закрыт, так что Коннер сможет пообедать там.</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:55: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:'812494c75d7a9d51',t:'MTY5NjY2NTMyMC4yMjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1100"]
1293B
1293
B
ru
B. JOE на телевидении!
<div class="problem-statement"><div class="header"><div class="title">B. JOE на телевидении!</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"><a href="https://www.youtube.com/watch?v=P2ZVC9aoiKo"><span class="tex-font-style-it">3R2 - Standby for Action</span></a></div></div><p>Наш владелец Кафе JOE Миллер скоро примет участие в новом игровом телешоу «1 против $$$n$$$».</p><p>Игра проходит в несколько раундов, где в каждом раунде ведущий задаёт JOE и его соперникам один общий вопрос. Все участники отвечающие неправильно выбывают из игры. Шоу заканчивается, когда остаётся только JOE (мы считаем, что JOE никогда не отвечает на вопрос неверно!).</p><p>Для каждого вопроса, на который отвечает JOE, если у него оставалось $$$s$$$ ($$$s &gt; 0$$$) соперников и из них $$$t$$$ ($$$0 \le t \le s$$$) ответили неверно, то JOE получает $$$\displaystyle\frac{t}{s}$$$ долларов. Ну а в следующем раунде у него будет уже $$$s - t$$$ соперников.</p><p>JOE задумался, чему равен наибольший приз, который он может получить в лучшем случае. Однако шоу начинается достаточно скоро, и у него нет на это времени. Может быть вы сможете ответить на этот вопрос?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит целое число $$$n$$$ ($$$1 \le n \le 10^5$$$), обозначающее число соперников JOE.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите наибольший возможный приз (в долларах), который может получить JOE.</p><p>Ваш ответ будет засчитан, если его абсолютная или относительная погрешность будет не более $$$10^{-4}$$$. Иначе говоря, если ваш ответ это $$$a$$$, а ответ жюри $$$b$$$, то должно выполняться $$$\frac{|a - b|}{max(1, b)} \le 10^{-4}$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1.000000000000 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1.500000000000 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Во втором примере наилучший сценарий выглядит следующим образом: один участник ошибается на первом вопросе, а второй на втором, тогда итоговый приз составит $$$\displaystyle \frac{1}{2} + \frac{1}{1} = 1.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="222d826f3e29db91cd1c3bb1f2967515"/> <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="f1f290e5f7b278d65660c115fd3c740ff743f745"/> <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='222d826f3e29db91cd1c3bb1f2967515'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1293%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='222d826f3e29db91cd1c3bb1f2967515'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1293">Codeforces Round 614 (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='222d826f3e29db91cd1c3bb1f2967515'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1293/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='222d826f3e29db91cd1c3bb1f2967515'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="519783"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='222d826f3e29db91cd1c3bb1f2967515'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="519783"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69012" title="Codeforces Round #614" target="_blank">Codeforces Round #614 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10303" resourceName="Codeforces Round #614" resourceManual="true" src="//codeforces.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/73051" title="Codeforces Round #614 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10314" resourceName="Codeforces Round #614 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/1293">Задачи</a></li> <li><a href="/contest/1293/submit">Отослать</a></li> <li><a href="/contest/1293/my">Мои посылки</a></li> <li><a href="/contest/1293/status">Статус</a></li> <li><a href="/contest/1293/hacks">Взломы</a></li> <li><a href="/contest/1293/room/1">Комната</a></li> <li><a href="/contest/1293/standings">Положение</a></li> <li><a href="/contest/1293/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d173490f81475a9690d0f063c36edba09d932bff"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. JOE на телевидении!</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"><a href="https://www.youtube.com/watch?v=P2ZVC9aoiKo"><span class="tex-font-style-it">3R2 - Standby for Action</span></a></div></div><p>Наш владелец Кафе JOE Миллер скоро примет участие в новом игровом телешоу «1 против $$$n$$$».</p><p>Игра проходит в несколько раундов, где в каждом раунде ведущий задаёт JOE и его соперникам один общий вопрос. Все участники отвечающие неправильно выбывают из игры. Шоу заканчивается, когда остаётся только JOE (мы считаем, что JOE никогда не отвечает на вопрос неверно!).</p><p>Для каждого вопроса, на который отвечает JOE, если у него оставалось $$$s$$$ ($$$s &gt; 0$$$) соперников и из них $$$t$$$ ($$$0 \le t \le s$$$) ответили неверно, то JOE получает $$$\displaystyle\frac{t}{s}$$$ долларов. Ну а в следующем раунде у него будет уже $$$s - t$$$ соперников.</p><p>JOE задумался, чему равен наибольший приз, который он может получить в лучшем случае. Однако шоу начинается достаточно скоро, и у него нет на это времени. Может быть вы сможете ответить на этот вопрос?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит целое число $$$n$$$ ($$$1 \le n \le 10^5$$$), обозначающее число соперников JOE.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите наибольший возможный приз (в долларах), который может получить JOE.</p><p>Ваш ответ будет засчитан, если его абсолютная или относительная погрешность будет не более $$$10^{-4}$$$. Иначе говоря, если ваш ответ это $$$a$$$, а ответ жюри $$$b$$$, то должно выполняться $$$\frac{|a - b|}{max(1, b)} \le 10^{-4}$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1.000000000000 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1.500000000000 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Во втором примере наилучший сценарий выглядит следующим образом: один участник ошибается на первом вопросе, а второй на втором, тогда итоговый приз составит $$$\displaystyle \frac{1}{2} + \frac{1}{1} = 1.5$$$ долларов.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:55:21</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'812494d30a0e4971',t:'MTY5NjY2NTMyMS41NjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1000"]
1293C
1293
C
ru
C. Игровой лабиринт Неко
<div class="problem-statement"><div class="header"><div class="title">C. Игровой лабиринт Неко</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><div class="epigraph"><div class="epigraph-text"><a href="https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak"><span class="tex-font-style-it">3R2 as DJ Mashiro - Happiness Breeze</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive"><span class="tex-font-style-it">Ice - DJ Mashiro is dead or alive</span></a></div></div><p>NEKO#ΦωΦ только что купила новую игру на свой компьютер!</p><p>Главный пазл этой игры это прямоугольный лабиринт $$$2 \times n$$$. Неко должна провести Некомими девочку из клетки $$$(1, 1)$$$ в клетку $$$(2, n)$$$, тем самым выбравшись из лабиринта. Девочка может переходить только между клетками, соседними по стороне.</p><p>Однако, в некоторые моменты игры, некоторые клетки меняют своё состояние: или из земли в лаву (которая не позволяет проходить через клетку), или наоборот (что делает клетку проходимой вновь). Изначально ни в одной клетке лавы нет.</p><p>Спустя часы стриминга Неко выяснила, что есть всего $$$q$$$ таких моментов, причём $$$i$$$-й из них переключает состояние клетки $$$(r_i, c_i)$$$ (с земли на лаву, или наоборот). Неко хочет узнать для каждого момента из этих $$$q$$$, можно ли после него пройти из клетки $$$(1, 1)$$$ в $$$(2, n)$$$ не проходя через клетки с лавой.</p><p>Неко великий игрок и стример, но она всё ещё не справляется с пазлами и задачками, требующими большой силы мозга. Не могли бы вы ей помочь?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$, $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$).</p><p>Среди следующих $$$q$$$ строк, $$$i$$$-я содержит целые числа $$$r_i$$$, $$$c_i$$$ ($$$1 \le r_i \le 2$$$, $$$1 \le c_i \le n$$$), обозначающие координаты клетки, меняющейся в $$$i$$$-й момент.</p><p>Гарантируется, что клетки $$$(1, 1)$$$ и $$$(2, n)$$$ никогда не будут даны в списке запросов.</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>» в зависимости от того, можно ли пройти от клетки $$$(1, 1)$$$ до $$$(2, n)$$$. Всего вам нужно вывести ровно $$$q$$$ ответов, по одному после каждого изменения.</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 2 3 1 4 2 4 2 3 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No No No Yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Разберём пример из условия:</p><ul> <li> После первого запроса девочка всё ещё может достичь цели, один из возможных путей выглядит как $$$(1,1) \to (1,2) \to (1,3) \to (1,4) \to (1,5) \to (2,5)$$$. </li><li> После второго запроса, добраться до цели невозможно, самая дальняя клетка, которой она может достичь, это $$$(1, 3)$$$. </li><li> После четвёртого запроса, клетка $$$(2, 3)$$$ уже не заблокирована, однако теперь заблокирован весь $$$4$$$-й столбец, так что достичь цели не получится. </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="1d11f97f1c40b39d39ea60656f205a23"/> <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="f1f290e5f7b278d65660c115fd3c740ff743f745"/> <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='1d11f97f1c40b39d39ea60656f205a23'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1293%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='1d11f97f1c40b39d39ea60656f205a23'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1293">Codeforces Round 614 (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='1d11f97f1c40b39d39ea60656f205a23'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1293/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='1d11f97f1c40b39d39ea60656f205a23'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="519784"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1d11f97f1c40b39d39ea60656f205a23'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="519784"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69012" title="Codeforces Round #614" target="_blank">Codeforces Round #614 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10303" resourceName="Codeforces Round #614" resourceManual="true" src="//codeforces.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/73051" title="Codeforces Round #614 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10314" resourceName="Codeforces Round #614 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/1293">Задачи</a></li> <li><a href="/contest/1293/submit">Отослать</a></li> <li><a href="/contest/1293/my">Мои посылки</a></li> <li><a href="/contest/1293/status">Статус</a></li> <li><a href="/contest/1293/hacks">Взломы</a></li> <li><a href="/contest/1293/room/1">Комната</a></li> <li><a href="/contest/1293/standings">Положение</a></li> <li><a href="/contest/1293/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ef164c859de1f8caed2d569af9ee7ba8f0f34786"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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.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><div class="epigraph"><div class="epigraph-text"><a href="https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak"><span class="tex-font-style-it">3R2 as DJ Mashiro - Happiness Breeze</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive"><span class="tex-font-style-it">Ice - DJ Mashiro is dead or alive</span></a></div></div><p>NEKO#ΦωΦ только что купила новую игру на свой компьютер!</p><p>Главный пазл этой игры это прямоугольный лабиринт $$$2 \times n$$$. Неко должна провести Некомими девочку из клетки $$$(1, 1)$$$ в клетку $$$(2, n)$$$, тем самым выбравшись из лабиринта. Девочка может переходить только между клетками, соседними по стороне.</p><p>Однако, в некоторые моменты игры, некоторые клетки меняют своё состояние: или из земли в лаву (которая не позволяет проходить через клетку), или наоборот (что делает клетку проходимой вновь). Изначально ни в одной клетке лавы нет.</p><p>Спустя часы стриминга Неко выяснила, что есть всего $$$q$$$ таких моментов, причём $$$i$$$-й из них переключает состояние клетки $$$(r_i, c_i)$$$ (с земли на лаву, или наоборот). Неко хочет узнать для каждого момента из этих $$$q$$$, можно ли после него пройти из клетки $$$(1, 1)$$$ в $$$(2, n)$$$ не проходя через клетки с лавой.</p><p>Неко великий игрок и стример, но она всё ещё не справляется с пазлами и задачками, требующими большой силы мозга. Не могли бы вы ей помочь?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$, $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$).</p><p>Среди следующих $$$q$$$ строк, $$$i$$$-я содержит целые числа $$$r_i$$$, $$$c_i$$$ ($$$1 \le r_i \le 2$$$, $$$1 \le c_i \le n$$$), обозначающие координаты клетки, меняющейся в $$$i$$$-й момент.</p><p>Гарантируется, что клетки $$$(1, 1)$$$ и $$$(2, n)$$$ никогда не будут даны в списке запросов.</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>» в зависимости от того, можно ли пройти от клетки $$$(1, 1)$$$ до $$$(2, n)$$$. Всего вам нужно вывести ровно $$$q$$$ ответов, по одному после каждого изменения.</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 2 3 1 4 2 4 2 3 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No No No Yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Разберём пример из условия:</p><ul> <li> После первого запроса девочка всё ещё может достичь цели, один из возможных путей выглядит как $$$(1,1) \to (1,2) \to (1,3) \to (1,4) \to (1,5) \to (2,5)$$$. </li><li> После второго запроса, добраться до цели невозможно, самая дальняя клетка, которой она может достичь, это $$$(1, 3)$$$. </li><li> После четвёртого запроса, клетка $$$(2, 3)$$$ уже не заблокирована, однако теперь заблокирован весь $$$4$$$-й столбец, так что достичь цели не получится. </li><li> После пятого запроса, проблемы со столбцом пропадают, так что она снова может добраться до цели. </li></ul></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:55: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:'812494dbae249d6a',t:'MTY5NjY2NTMyMi44OTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1400"]
1293D
1293
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><div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/hyouryu"><span class="tex-font-style-it">THE SxPLAY &amp; KIVΛ - 漂流</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/perspectives"><span class="tex-font-style-it">KIVΛ &amp; Nikki Simmons - Perspectives</span></a></div></div><p>С новым телом наш идол Арома Белая (или лучше было сказать Каори Минамийа?) начинает восстанавливать своё потерянное прошлое через OS-пространство.</p><p>Это пространство можно представить как 2D плоскость, с бесконечным количеством устройств с данными, пронумерованных с $$$0$$$. Координаты устройств можно описать следующим образом:</p><ul> <li> Координаты $$$0$$$-го устройства равны $$$(x_0, y_0)$$$ </li><li> Для $$$i &gt; 0$$$, координаты $$$i$$$-го устройства равны $$$(a_x \cdot x_{i-1} + b_x, a_y \cdot y_{i-1} + b_y)$$$ </li></ul><p>Изначально Арома расположена в точке $$$(x_s, y_s)$$$. Она может находиться в OS-пространстве не более $$$t$$$ секунд, после этого ей придётся вернуться в реальный мир. Чтобы вернутся в реальный мир <span class="tex-font-style-bf">не требуется</span> возвращаться в изначальную точку $$$(x_s, y_s)$$$.</p><p>Внутри OS-пространства Арома может делать следующие действия:</p><ul> <li> Из точки $$$(x, y)$$$ Арома может перейти в одну из следующих точек $$$(x-1, y)$$$, $$$(x+1, y)$$$, $$$(x, y-1)$$$ или $$$(x, y+1)$$$. Это действие занимает $$$1$$$ секунду. </li><li> Если Арома стоит в точке с устройством, то она может его собрать. Можно считать, что это действие занимает $$$0$$$ секунд. Разумеется, каждое устройство можно собрать не более одного раза. </li></ul><p>Арома хочет собрать как можно больше данных перед тем как вернётся назад. Помогите ей определить максимальное количество устройств с данными, которые она сможет собрать за $$$t$$$ секунд.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$x_0$$$, $$$y_0$$$, $$$a_x$$$, $$$a_y$$$, $$$b_x$$$, $$$b_y$$$ ($$$1 \leq x_0, y_0 \leq 10^{16}$$$, $$$2 \leq a_x, a_y \leq 100$$$, $$$0 \leq b_x, b_y \leq 10^{16}$$$), которые задают координаты устройств с данными.</p><p>Вторая строка содержит целые числа $$$x_s$$$, $$$y_s$$$, $$$t$$$ ($$$1 \leq x_s, y_s, t \leq 10^{16}$$$), изначальные координаты Аромы и доступное время.</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> 1 1 2 3 1 0 2 4 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3</pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 2 3 1 0 15 27 26 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 2 3 1 0 2 2 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>Во всех трёх примерах, координаты первых $$$5$$$ устройств равны $$$(1, 1)$$$, $$$(3, 3)$$$, $$$(7, 9)$$$, $$$(15, 27)$$$ и $$$(31, 81)$$$ (напомним, что устройства пронумерованы начиная с $$$0$$$).</p><p>В первом примере оптимальный маршрут чтобы собрать $$$3$$$ вершины выглядит следующим образом: </p><ul> <li> Перейти в точку $$$(3, 3)$$$ и собрать $$$1$$$-е устройство. Это занимает $$$|3 - 2| + |3 - 4| = 2$$$ секунд. </li><li> Перейти в точку $$$(1, 1)$$$ и собрать $$$0$$$-е устройство. Это занимает $$$|1 - 3| + |1 - 3| = 4$$$ секунд. </li><li> Перейти в точку $$$(7, 9)$$$ и собрать $$$2$$$-е устройство. Это занимает $$$|7 - 1| + |9 - 1| = 14$$$ секунд. </li></ul><p>Во втором примере оптимальный маршрут чтобы собрать $$$2$$$ вершины выглядит следующим образом: </p><ul> <li> Собрать $$$3$$$-е устройство. Это занимает ноль секунд. </li><li> Перейти в точку $$$(7, 9)$$$ и собрать $$$2$$$-е устройство. Это занимает $$$|15 - 7| + |27 - 9| = 26$$$ секунд. </li></ul><p>В третьем примере Арома не может собрать ни одного устройства. Пожалуй стоило отдохнуть, а не рваться в OS-пространство без подготовки.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="68c65d5e6a46597b2e8f80cc219c7371"/> <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="f1f290e5f7b278d65660c115fd3c740ff743f745"/> <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='68c65d5e6a46597b2e8f80cc219c7371'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1293%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='68c65d5e6a46597b2e8f80cc219c7371'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1293">Codeforces Round 614 (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='68c65d5e6a46597b2e8f80cc219c7371'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1293/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='68c65d5e6a46597b2e8f80cc219c7371'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="519785"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='68c65d5e6a46597b2e8f80cc219c7371'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="519785"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69012" title="Codeforces Round #614" target="_blank">Codeforces Round #614 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10303" resourceName="Codeforces Round #614" resourceManual="true" src="//codeforces.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/73051" title="Codeforces Round #614 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10314" resourceName="Codeforces Round #614 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/1293">Задачи</a></li> <li><a href="/contest/1293/submit">Отослать</a></li> <li><a href="/contest/1293/my">Мои посылки</a></li> <li><a href="/contest/1293/status">Статус</a></li> <li><a href="/contest/1293/hacks">Взломы</a></li> <li><a href="/contest/1293/room/1">Комната</a></li> <li><a href="/contest/1293/standings">Положение</a></li> <li><a href="/contest/1293/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c4753e94607e8a8b7734c57583a0dc5fea90fa3f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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><div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/hyouryu"><span class="tex-font-style-it">THE SxPLAY &amp; KIVΛ - 漂流</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/perspectives"><span class="tex-font-style-it">KIVΛ &amp; Nikki Simmons - Perspectives</span></a></div></div><p>С новым телом наш идол Арома Белая (или лучше было сказать Каори Минамийа?) начинает восстанавливать своё потерянное прошлое через OS-пространство.</p><p>Это пространство можно представить как 2D плоскость, с бесконечным количеством устройств с данными, пронумерованных с $$$0$$$. Координаты устройств можно описать следующим образом:</p><ul> <li> Координаты $$$0$$$-го устройства равны $$$(x_0, y_0)$$$ </li><li> Для $$$i &gt; 0$$$, координаты $$$i$$$-го устройства равны $$$(a_x \cdot x_{i-1} + b_x, a_y \cdot y_{i-1} + b_y)$$$ </li></ul><p>Изначально Арома расположена в точке $$$(x_s, y_s)$$$. Она может находиться в OS-пространстве не более $$$t$$$ секунд, после этого ей придётся вернуться в реальный мир. Чтобы вернутся в реальный мир <span class="tex-font-style-bf">не требуется</span> возвращаться в изначальную точку $$$(x_s, y_s)$$$.</p><p>Внутри OS-пространства Арома может делать следующие действия:</p><ul> <li> Из точки $$$(x, y)$$$ Арома может перейти в одну из следующих точек $$$(x-1, y)$$$, $$$(x+1, y)$$$, $$$(x, y-1)$$$ или $$$(x, y+1)$$$. Это действие занимает $$$1$$$ секунду. </li><li> Если Арома стоит в точке с устройством, то она может его собрать. Можно считать, что это действие занимает $$$0$$$ секунд. Разумеется, каждое устройство можно собрать не более одного раза. </li></ul><p>Арома хочет собрать как можно больше данных перед тем как вернётся назад. Помогите ей определить максимальное количество устройств с данными, которые она сможет собрать за $$$t$$$ секунд.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$x_0$$$, $$$y_0$$$, $$$a_x$$$, $$$a_y$$$, $$$b_x$$$, $$$b_y$$$ ($$$1 \leq x_0, y_0 \leq 10^{16}$$$, $$$2 \leq a_x, a_y \leq 100$$$, $$$0 \leq b_x, b_y \leq 10^{16}$$$), которые задают координаты устройств с данными.</p><p>Вторая строка содержит целые числа $$$x_s$$$, $$$y_s$$$, $$$t$$$ ($$$1 \leq x_s, y_s, t \leq 10^{16}$$$), изначальные координаты Аромы и доступное время.</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> 1 1 2 3 1 0 2 4 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3</pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 2 3 1 0 15 27 26 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 2 3 1 0 2 2 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>Во всех трёх примерах, координаты первых $$$5$$$ устройств равны $$$(1, 1)$$$, $$$(3, 3)$$$, $$$(7, 9)$$$, $$$(15, 27)$$$ и $$$(31, 81)$$$ (напомним, что устройства пронумерованы начиная с $$$0$$$).</p><p>В первом примере оптимальный маршрут чтобы собрать $$$3$$$ вершины выглядит следующим образом: </p><ul> <li> Перейти в точку $$$(3, 3)$$$ и собрать $$$1$$$-е устройство. Это занимает $$$|3 - 2| + |3 - 4| = 2$$$ секунд. </li><li> Перейти в точку $$$(1, 1)$$$ и собрать $$$0$$$-е устройство. Это занимает $$$|1 - 3| + |1 - 3| = 4$$$ секунд. </li><li> Перейти в точку $$$(7, 9)$$$ и собрать $$$2$$$-е устройство. Это занимает $$$|7 - 1| + |9 - 1| = 14$$$ секунд. </li></ul><p>Во втором примере оптимальный маршрут чтобы собрать $$$2$$$ вершины выглядит следующим образом: </p><ul> <li> Собрать $$$3$$$-е устройство. Это занимает ноль секунд. </li><li> Перейти в точку $$$(7, 9)$$$ и собрать $$$2$$$-е устройство. Это занимает $$$|15 - 7| + |27 - 9| = 26$$$ секунд. </li></ul><p>В третьем примере Арома не может собрать ни одного устройства. Пожалуй стоило отдохнуть, а не рваться в OS-пространство без подготовки.</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:55: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:'812494e3cda116ab',t:'MTY5NjY2NTMyNC4xODAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1700"]
1293E
1293
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><div class="epigraph"><div class="epigraph-text"><a href="https://www.youtube.com/watch?v=kwsciXm_7sA"><span class="tex-font-style-it">INSPION FullBand Master - INSPION</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://www.youtube.com/watch?v=kwsciXm_7sA"><span class="tex-font-style-it">INSPION - IOLITE-SUNSTONE</span></a></div></div><p>На другом этаже A.R.C. Markland-N, молодой человек Саймон "Ксенон" Джексон отдыхает, завершив свои работы по проекту быстрее запланированного (впрочем как всегда). Так как свободного времени достаточно много, он надевает свой легендарный хакерский "X" инстинкт и бежит сражаться против банд кибермира.</p><p>Его целью является сеть из $$$n$$$ небольших банд. Их сеть состоит из ровно $$$n - 1$$$ прямых соединений, каждое из которых связывает какие-то две банды вместе. Соединения устроены таким образом, что любые две банды соединены через последовательность прямых соединений.</p><p>Изучая данные, Ксенон понял, что банды используют для самозащиты следующую форму шифрования. Каждому соединению назначено целое число от $$$0$$$ до $$$n - 2$$$, таким образом, что все назначенные числа различны, а каждое число назначено какому-то соединению. Если атакующий пытается получить доступ к защищённым данным, то ему придётся прорваться через $$$S$$$ слоёв с паролями, где $$$S$$$ определяется как:</p><p>$$$$$$S = \sum_{1 \leq u &lt; v \leq n} mex(u, v)$$$$$$</p><p>Здесь $$$mex(u, v)$$$ обозначает наименьшее неотрицательное целое число, которое не встречается на соединениях на единственном простом пути между бандами $$$u$$$ и $$$v$$$.</p><p>Ксенон не знает каким образом числа были назначены соединениям, но это не проблема. Он собирается поручить своим AI перебрать и взломать все пароли, но перед этим он хочет знать чему равно наибольшее возможное значение $$$S$$$, чтобы настроить AI наиболее эффективно.</p><p>Сейчас Ксенон ушёл писать скрипты для AI, и он собирается их закончить в течение двух часов. Не могли бы вы найти наибольшее значение $$$S$$$ перед тем, как он вернётся?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \leq n \leq 3000$$$) — количество банд в сети.</p><p>Каждая из следующих $$$n - 1$$$ строк содержит числа $$$u_i$$$ и $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$; $$$u_i \neq v_i$$$), обозначающие прямое соединение между бандами $$$u_i$$$ и $$$v_i$$$.</p><p>Гарантируется, что связи расположены таким образом, что каждая пара банд соединена ровно одним простым путём.</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> 3 1 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 1 3 1 4 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно достичь максимального $$$S$$$ следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/421d2b1ce0e02f683a77f84bb33a92ce5968e710.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В этой сети, $$$mex(1, 2) = 0$$$, $$$mex(1, 3) = 2$$$ и $$$mex(2, 3) = 1$$$. Таким образом, $$$S = 0 + 2 + 1 = 3$$$.</p><p>Во втором примере можно достичь максимального $$$S$$$ таким образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fa27194eb402038a92a3b9fb5077487aac71d934.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В этой сети все ненулевые значения mex перечислены ниже: </p><ul> <li> $$$mex(1, 3) = 1$$$ </li><li> $$$mex(1, 5) = 2$$$ </li><li> $$$mex(2, 3) = 1$$$ </li><li> $$$mex(2, 5) = 2$$$ </li><li> $$$mex(3, 4) = 1$$$ </li><li> $$$mex(4, 5) = 3$$$ </li></ul><p>Таким образом, $$$S = 1 + 2 + 1 + 2 + 1 + 3 = 10$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="d39ebba17de260e4054ce01eb5e20c8e"/> <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="f1f290e5f7b278d65660c115fd3c740ff743f745"/> <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='d39ebba17de260e4054ce01eb5e20c8e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1293%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='d39ebba17de260e4054ce01eb5e20c8e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1293">Codeforces Round 614 (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='d39ebba17de260e4054ce01eb5e20c8e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1293/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound 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='d39ebba17de260e4054ce01eb5e20c8e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="519786"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d39ebba17de260e4054ce01eb5e20c8e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="519786"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69012" title="Codeforces Round #614" target="_blank">Codeforces Round #614 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10303" resourceName="Codeforces Round #614" resourceManual="true" src="//codeforces.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/73051" title="Codeforces Round #614 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10314" resourceName="Codeforces Round #614 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/1293">Задачи</a></li> <li><a href="/contest/1293/submit">Отослать</a></li> <li><a href="/contest/1293/my">Мои посылки</a></li> <li><a href="/contest/1293/status">Статус</a></li> <li><a href="/contest/1293/hacks">Взломы</a></li> <li><a href="/contest/1293/room/1">Комната</a></li> <li><a href="/contest/1293/standings">Положение</a></li> <li><a href="/contest/1293/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c8a35518493e6648a56264127ee23cb90479a3ef"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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><div class="epigraph"><div class="epigraph-text"><a href="https://www.youtube.com/watch?v=kwsciXm_7sA"><span class="tex-font-style-it">INSPION FullBand Master - INSPION</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://www.youtube.com/watch?v=kwsciXm_7sA"><span class="tex-font-style-it">INSPION - IOLITE-SUNSTONE</span></a></div></div><p>На другом этаже A.R.C. Markland-N, молодой человек Саймон &quot;Ксенон&quot; Джексон отдыхает, завершив свои работы по проекту быстрее запланированного (впрочем как всегда). Так как свободного времени достаточно много, он надевает свой легендарный хакерский &quot;X&quot; инстинкт и бежит сражаться против банд кибермира.</p><p>Его целью является сеть из $$$n$$$ небольших банд. Их сеть состоит из ровно $$$n - 1$$$ прямых соединений, каждое из которых связывает какие-то две банды вместе. Соединения устроены таким образом, что любые две банды соединены через последовательность прямых соединений.</p><p>Изучая данные, Ксенон понял, что банды используют для самозащиты следующую форму шифрования. Каждому соединению назначено целое число от $$$0$$$ до $$$n - 2$$$, таким образом, что все назначенные числа различны, а каждое число назначено какому-то соединению. Если атакующий пытается получить доступ к защищённым данным, то ему придётся прорваться через $$$S$$$ слоёв с паролями, где $$$S$$$ определяется как:</p><p>$$$$$$S = \sum_{1 \leq u &lt; v \leq n} mex(u, v)$$$$$$</p><p>Здесь $$$mex(u, v)$$$ обозначает наименьшее неотрицательное целое число, которое не встречается на соединениях на единственном простом пути между бандами $$$u$$$ и $$$v$$$.</p><p>Ксенон не знает каким образом числа были назначены соединениям, но это не проблема. Он собирается поручить своим AI перебрать и взломать все пароли, но перед этим он хочет знать чему равно наибольшее возможное значение $$$S$$$, чтобы настроить AI наиболее эффективно.</p><p>Сейчас Ксенон ушёл писать скрипты для AI, и он собирается их закончить в течение двух часов. Не могли бы вы найти наибольшее значение $$$S$$$ перед тем, как он вернётся?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \leq n \leq 3000$$$) — количество банд в сети.</p><p>Каждая из следующих $$$n - 1$$$ строк содержит числа $$$u_i$$$ и $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$; $$$u_i \neq v_i$$$), обозначающие прямое соединение между бандами $$$u_i$$$ и $$$v_i$$$.</p><p>Гарантируется, что связи расположены таким образом, что каждая пара банд соединена ровно одним простым путём.</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> 3 1 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 1 3 1 4 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно достичь максимального $$$S$$$ следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/421d2b1ce0e02f683a77f84bb33a92ce5968e710.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В этой сети, $$$mex(1, 2) = 0$$$, $$$mex(1, 3) = 2$$$ и $$$mex(2, 3) = 1$$$. Таким образом, $$$S = 0 + 2 + 1 = 3$$$.</p><p>Во втором примере можно достичь максимального $$$S$$$ таким образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fa27194eb402038a92a3b9fb5077487aac71d934.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В этой сети все ненулевые значения mex перечислены ниже: </p><ul> <li> $$$mex(1, 3) = 1$$$ </li><li> $$$mex(1, 5) = 2$$$ </li><li> $$$mex(2, 3) = 1$$$ </li><li> $$$mex(2, 5) = 2$$$ </li><li> $$$mex(3, 4) = 1$$$ </li><li> $$$mex(4, 5) = 3$$$ </li></ul><p>Таким образом, $$$S = 1 + 2 + 1 + 2 + 1 + 3 = 10$$$.</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:55:25</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'812494ebcc317903',t:'MTY5NjY2NTMyNS40ODMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "*2300"]
1293F
1293
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 href="https://soundcloud.com/kivawu/aesir-chaos"><span class="tex-font-style-it">Æsir - CHAOS</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/aesir-v"><span class="tex-font-style-it">Æsir - V.</span></a></div></div><p><span class="tex-font-style-it">«Всё было спланировано, Никаких больше скрытых забот. Состояние Цитуса тоже совершенно..»</span></p><p><span class="tex-font-style-it">Текущее время...... 00:01:12......</span></p><p><span class="tex-font-style-it">Время пришло.</span></p><p>Образцов эмоций теперь достаточно. Прошло почти три года, и пришло время для Айви разбудить свою связанную сестру Ванессу.</p><p>Система внутри библиотеки A.R.C. может быть представлена как неориентированный граф с бесконечным числом обрабатывающих вершин, пронумерованных последовательными положительными целыми числами ($$$1, 2, 3, \ldots$$$). Вершина с номером $$$x$$$ ($$$x &gt; 1$$$) напрямую соединена с вершиной с номером $$$\frac{x}{f(x)}$$$, где $$$f(x)$$$ обозначает наименьший простой делитель $$$x$$$.</p><p>Разум Ванессы разделён на $$$n$$$ фрагментов. Спустя более 500 лет в коме, фрагменты несколько подраскидало: $$$i$$$-й фрагмент теперь находится в вершине с номером $$$k_i!$$$ (факториал $$$k_i$$$).</p><p>Чтобы максимизировать шансы успешного пробуждения, Айви хочет разместить образцы эмоций в вершине $$$P$$$, такой что суммарная длина всех путей от каждого фрагмента до $$$P$$$ является минимально возможной. В случае если несколько фрагментов расположены в одной и той же вершине, путь от них до $$$P$$$ учитывается несколько раз.</p><p>В мире нулей и единиц такое требование вполне тривиально для Айви. Не более, чем секундой позже, она уже нашла такую вершину.</p><p>Возможно ли такое же для простого смертного как вы?</p><p>Для простоты, найдите минимальную суммарную длину путей от каждого фрагмента до оптимальной вершины $$$P$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 10^6$$$) — количество фрагментов в разуме Ванессы.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$k_1, k_2, \ldots, k_n$$$ ($$$0 \le k_i \le 5000$$$), задающие вершины содержащие фрагменты разума Ванессы: $$$i$$$-й фрагмент расположен в вершине $$$k_i!$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, обозначающее минимальную сумму путей от фрагментов до вершины с образцами эмоций $$$P$$$.</p><p>Напомним, что если несколько фрагментов расположены в одной вершины, то расстояние от этой вершины до $$$P$$$ нужно учесть несколько раз.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 4 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первые $$$24$$$ вершины системы выглядят следующим образом (вершины $$$1!$$$, $$$2!$$$, $$$3!$$$, $$$4!$$$ обозначены жирным):</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/043302b7f3870a8689d82fdc00b8b7beb0fada68.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>В первом примере Айви может разместить образцы эмоций в вершине $$$1$$$, тогда:</p><ul> <li> Расстояние от первого фрагмента Ванессы до вершины $$$1$$$ равно $$$1$$$. </li><li> Расстояние от второго фрагмента Ванессы до вершины $$$1$$$ равно $$$0$$$. </li><li> Расстояние от третьего фрагмента Ванессы до вершины $$$1$$$ равно $$$4$$$. </li></ul><p>Суммарная длина равна $$$5$$$.</p><p>Во втором примере Айви оптимальной вершина для сбора является $$$6$$$:</p><ul> <li> Расстояние от первого фрагмента Ванессы до вершины $$$6$$$ равно $$$0$$$. </li><li> Расстояние от второго фрагмента Ванессы до вершины $$$6$$$ равно $$$2$$$.. </li><li> Расстояние от третьего фрагмента Ванессы до вершины $$$6$$$ равно $$$2$$$. </li><li> Расстояние от четвёртого фрагмента Ванессы до вершины $$$6$$$ снова равно $$$2$$$. </li></ul><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="9c51b270455fc8e71aac95a92026e12a"/> <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="f1f290e5f7b278d65660c115fd3c740ff743f745"/> <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='9c51b270455fc8e71aac95a92026e12a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1293%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='9c51b270455fc8e71aac95a92026e12a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1293">Codeforces Round 614 (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='9c51b270455fc8e71aac95a92026e12a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1293/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='9c51b270455fc8e71aac95a92026e12a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="519787"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9c51b270455fc8e71aac95a92026e12a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="519787"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69012" title="Codeforces Round #614" target="_blank">Codeforces Round #614 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10303" resourceName="Codeforces Round #614" resourceManual="true" src="//codeforces.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/73051" title="Codeforces Round #614 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10314" resourceName="Codeforces Round #614 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/1293">Задачи</a></li> <li><a href="/contest/1293/submit">Отослать</a></li> <li><a href="/contest/1293/my">Мои посылки</a></li> <li><a href="/contest/1293/status">Статус</a></li> <li><a href="/contest/1293/hacks">Взломы</a></li> <li><a href="/contest/1293/room/1">Комната</a></li> <li><a href="/contest/1293/standings">Положение</a></li> <li><a href="/contest/1293/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a4ba712056385b3e656f53ab3b4d4db002dd09b9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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 href="https://soundcloud.com/kivawu/aesir-chaos"><span class="tex-font-style-it">Æsir - CHAOS</span></a></div></div> <div class="epigraph"><div class="epigraph-text"><a href="https://soundcloud.com/kivawu/aesir-v"><span class="tex-font-style-it">Æsir - V.</span></a></div></div><p><span class="tex-font-style-it">«Всё было спланировано, Никаких больше скрытых забот. Состояние Цитуса тоже совершенно..»</span></p><p><span class="tex-font-style-it">Текущее время...... 00:01:12......</span></p><p><span class="tex-font-style-it">Время пришло.</span></p><p>Образцов эмоций теперь достаточно. Прошло почти три года, и пришло время для Айви разбудить свою связанную сестру Ванессу.</p><p>Система внутри библиотеки A.R.C. может быть представлена как неориентированный граф с бесконечным числом обрабатывающих вершин, пронумерованных последовательными положительными целыми числами ($$$1, 2, 3, \ldots$$$). Вершина с номером $$$x$$$ ($$$x &gt; 1$$$) напрямую соединена с вершиной с номером $$$\frac{x}{f(x)}$$$, где $$$f(x)$$$ обозначает наименьший простой делитель $$$x$$$.</p><p>Разум Ванессы разделён на $$$n$$$ фрагментов. Спустя более 500 лет в коме, фрагменты несколько подраскидало: $$$i$$$-й фрагмент теперь находится в вершине с номером $$$k_i!$$$ (факториал $$$k_i$$$).</p><p>Чтобы максимизировать шансы успешного пробуждения, Айви хочет разместить образцы эмоций в вершине $$$P$$$, такой что суммарная длина всех путей от каждого фрагмента до $$$P$$$ является минимально возможной. В случае если несколько фрагментов расположены в одной и той же вершине, путь от них до $$$P$$$ учитывается несколько раз.</p><p>В мире нулей и единиц такое требование вполне тривиально для Айви. Не более, чем секундой позже, она уже нашла такую вершину.</p><p>Возможно ли такое же для простого смертного как вы?</p><p>Для простоты, найдите минимальную суммарную длину путей от каждого фрагмента до оптимальной вершины $$$P$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 10^6$$$) — количество фрагментов в разуме Ванессы.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$k_1, k_2, \ldots, k_n$$$ ($$$0 \le k_i \le 5000$$$), задающие вершины содержащие фрагменты разума Ванессы: $$$i$$$-й фрагмент расположен в вершине $$$k_i!$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, обозначающее минимальную сумму путей от фрагментов до вершины с образцами эмоций $$$P$$$.</p><p>Напомним, что если несколько фрагментов расположены в одной вершины, то расстояние от этой вершины до $$$P$$$ нужно учесть несколько раз.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 4 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первые $$$24$$$ вершины системы выглядят следующим образом (вершины $$$1!$$$, $$$2!$$$, $$$3!$$$, $$$4!$$$ обозначены жирным):</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/043302b7f3870a8689d82fdc00b8b7beb0fada68.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>В первом примере Айви может разместить образцы эмоций в вершине $$$1$$$, тогда:</p><ul> <li> Расстояние от первого фрагмента Ванессы до вершины $$$1$$$ равно $$$1$$$. </li><li> Расстояние от второго фрагмента Ванессы до вершины $$$1$$$ равно $$$0$$$. </li><li> Расстояние от третьего фрагмента Ванессы до вершины $$$1$$$ равно $$$4$$$. </li></ul><p>Суммарная длина равна $$$5$$$.</p><p>Во втором примере Айви оптимальной вершина для сбора является $$$6$$$:</p><ul> <li> Расстояние от первого фрагмента Ванессы до вершины $$$6$$$ равно $$$0$$$. </li><li> Расстояние от второго фрагмента Ванессы до вершины $$$6$$$ равно $$$2$$$.. </li><li> Расстояние от третьего фрагмента Ванессы до вершины $$$6$$$ равно $$$2$$$. </li><li> Расстояние от четвёртого фрагмента Ванессы до вершины $$$6$$$ снова равно $$$2$$$. </li></ul><p>Суммарная длина равна $$$6$$$.</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:55: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:'812494f409667a79',t:'MTY5NjY2NTMyNi44NjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\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"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2700"]
1294A
1294
A
ru
A. Коллекционирование монет
<div class="problem-statement"><div class="header"><div class="title">A. Коллекционирование монет</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Поликарпа есть три сестры: Алиса, Барбара и Серена. Они коллекционируют монеты. Сейчас у Алисы есть $$$a$$$ монет, у Барбары — $$$b$$$ монет и у Серены — $$$c$$$ монет. Недавно Поликарп вернулся из кругосветного путешествия, во время которого приобрел $$$n$$$ монет. </p><p>Он хочет распределить <span class="tex-font-style-bf">все</span> эти $$$n$$$ монет между сестрами так, чтобы после этого количество монет у Алисы было равным количеству монет у Барбары, а также было равным количеству монет у Серены. Другими словами, если Поликарп отдаст $$$A$$$ монет Алисе, $$$B$$$ монет Барбаре и $$$C$$$ монет Серене ($$$A+B+C=n$$$), то $$$a + A = b + B = c + C$$$. Ваша задача — определить, возможно ли распределить <span class="tex-font-style-bf">все</span> $$$n$$$ монеты между сестрами способом, описанным выше.</p><p><span class="tex-font-style-bf">Заметьте</span>, что A, B или C (количество монет, которые Поликарп дает Алисе, Барбаре и Серене соответственно) могут быть равны 0. </p><p>Вам нужно ответить на $$$t$$$ независимых наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных. Следующие $$$t$$$ строк описывают наборы входных данных. Каждый набор входных данных начинается с новой строки и состоит из четырех разделенных между собой пробелами целых чисел $$$a, b, c$$$ и $$$n$$$ ($$$1 \le a, b, c, n \le 10^8$$$) — количество монет у Алисы, количество монет у Барбары, количество монет у Серены и количество монет у Поликарпа.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">YES</span>», если Поликарп может распределить <span class="tex-font-style-bf">все</span> $$$n$$$ монеты между своими сестрами и «<span class="tex-font-style-tt">NO</span>» в противном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 3 2 8 100 101 102 105 3 2 1 100000000 10 20 15 14 101 101 101 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES NO NO YES </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="db6925f0926a1fad50cc45d35fa56070"/> <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="834b33f4ae46a58d99d89ad4030429b17e8c259e"/> <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='db6925f0926a1fad50cc45d35fa56070'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1294%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='db6925f0926a1fad50cc45d35fa56070'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1294">Codeforces Round 615 (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='db6925f0926a1fad50cc45d35fa56070'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1294/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='db6925f0926a1fad50cc45d35fa56070'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="521707"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='db6925f0926a1fad50cc45d35fa56070'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="521707"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73211" title="Codeforces Round #615 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10315:10316" 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/73274" title="Разбор Codeforces Round #615 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="11508:11509" 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/1294">Задачи</a></li> <li><a href="/contest/1294/submit">Отослать</a></li> <li><a href="/contest/1294/my">Мои посылки</a></li> <li><a href="/contest/1294/status">Статус</a></li> <li><a href="/contest/1294/hacks">Взломы</a></li> <li><a href="/contest/1294/standings">Положение</a></li> <li><a href="/contest/1294/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_350f571ac37743043f7c473c410e224dcfd9308b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Коллекционирование монет</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Поликарпа есть три сестры: Алиса, Барбара и Серена. Они коллекционируют монеты. Сейчас у Алисы есть $$$a$$$ монет, у Барбары — $$$b$$$ монет и у Серены — $$$c$$$ монет. Недавно Поликарп вернулся из кругосветного путешествия, во время которого приобрел $$$n$$$ монет. </p><p>Он хочет распределить <span class="tex-font-style-bf">все</span> эти $$$n$$$ монет между сестрами так, чтобы после этого количество монет у Алисы было равным количеству монет у Барбары, а также было равным количеству монет у Серены. Другими словами, если Поликарп отдаст $$$A$$$ монет Алисе, $$$B$$$ монет Барбаре и $$$C$$$ монет Серене ($$$A+B+C=n$$$), то $$$a + A = b + B = c + C$$$. Ваша задача — определить, возможно ли распределить <span class="tex-font-style-bf">все</span> $$$n$$$ монеты между сестрами способом, описанным выше.</p><p><span class="tex-font-style-bf">Заметьте</span>, что A, B или C (количество монет, которые Поликарп дает Алисе, Барбаре и Серене соответственно) могут быть равны 0. </p><p>Вам нужно ответить на $$$t$$$ независимых наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных. Следующие $$$t$$$ строк описывают наборы входных данных. Каждый набор входных данных начинается с новой строки и состоит из четырех разделенных между собой пробелами целых чисел $$$a, b, c$$$ и $$$n$$$ ($$$1 \le a, b, c, n \le 10^8$$$) — количество монет у Алисы, количество монет у Барбары, количество монет у Серены и количество монет у Поликарпа.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">YES</span>», если Поликарп может распределить <span class="tex-font-style-bf">все</span> $$$n$$$ монеты между своими сестрами и «<span class="tex-font-style-tt">NO</span>» в противном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 3 2 8 100 101 102 105 3 2 1 100000000 10 20 15 14 101 101 101 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES NO NO YES </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:55: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:'812494fc9ff49d61',t:'MTY5NjY2NTMyOC4yMzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1294B
1294
B
ru
B. Сбор посылок
<div class="problem-statement"><div class="header"><div class="title">B. Сбор посылок</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На складе есть робот и $$$n$$$ посылок, которые он хочет собрать. Склад можно представить в виде координатной сетки. Изначально робот находится в точке $$$(0, 0)$$$. $$$i$$$-я посылка находится в точке $$$(x_i, y_i)$$$. Гарантируется, что в одной точке не могут находиться две посылки. Также гарантируется, что в точке $$$(0, 0)$$$ посылки нет.</p><p>Робот наполовину сломан и может передвигаться только вверх ('<span class="tex-font-style-tt">U</span>') и вправо ('<span class="tex-font-style-tt">R</span>'). Другими словами, за один шаг робот может переместиться из точки $$$(x, y)$$$ в точку ($$$x + 1, y$$$) или в точку $$$(x, y + 1)$$$. Как сказано выше, робот хочет собрать все $$$n$$$ посылок (<span class="tex-font-style-bf">в любом порядке</span>). Он хочет сделать это за минимально возможное число шагов. Если существует несколько подходящих последовательностей шагов, робот хочет выбрать лексикографически минимальный путь.</p><p>Строка $$$s$$$ длины $$$n$$$ лексикографически меньше, чем строка $$$t$$$ длины $$$n$$$ если существует такой индекс $$$1 \le j \le n$$$, что для всех $$$i$$$ от $$$1$$$ до $$$j-1$$$ $$$s_i = t_i$$$ и $$$s_j &lt; t_j$$$. Это обычное сравнение строк, например, в словаре строки расположены в лексикографическом порядке. Большинство языков программирования сравнивают строки именно так.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 1000$$$) — количество посылок на складе.</p><p>Следующие $$$n$$$ строк содержат описания посылок. $$$i$$$-я посылка задана в виде двух целых чисел $$$x_i$$$ и $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) — $$$x$$$-координаты посылки и $$$y$$$-координаты посылки.</p><p>Гарантируется, что в каждой точке находится не более одной посылки. Также гарантируется, что в точке $$$(0, 0)$$$ посылки нет.</p><p>Сумма $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$1000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите ответ.</p><p>Если невозможно собрать все $$$n$$$ посылок в каком-либо порядке, стартуя из точки ($$$0,0$$$), выведите «<span class="tex-font-style-tt">NO</span>» первой строкой.</p><p>Иначе выведите «<span class="tex-font-style-tt">YES</span>» первой строкой. Затем выведите <span class="tex-font-style-bf">кратчайший</span> путь (строку), состоящий из символов '<span class="tex-font-style-tt">R</span>' и '<span class="tex-font-style-tt">U</span>'. Среди всех таких путей нужно выбрать лексикографически минимальный.</p><p><span class="tex-font-style-bf">Заметьте, что в этой задаче «<span class="tex-font-style-tt">YES</span>» и «<span class="tex-font-style-tt">NO</span>» могут быть выведены только в верхнем регистре, то есть «<span class="tex-font-style-tt">Yes</span>», «<span class="tex-font-style-tt">no</span>» и «<span class="tex-font-style-tt">YeS</span>» не принимаются</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 1 3 1 2 3 3 5 5 4 3 2 1 0 0 1 1 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES RUUURRRRUU NO YES RRRRUUU </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора данных из указанного примера оптимальный путь <span class="tex-font-style-tt">RUUURRRRUU</span> выглядит следующим образом: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8ba8beb3d4798d0c00f093234601e29f45df5fd2.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="7db60a7b0b918283381b8bf849fcfc9c"/> <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="834b33f4ae46a58d99d89ad4030429b17e8c259e"/> <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='7db60a7b0b918283381b8bf849fcfc9c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1294%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='7db60a7b0b918283381b8bf849fcfc9c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1294">Codeforces Round 615 (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='7db60a7b0b918283381b8bf849fcfc9c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1294/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='7db60a7b0b918283381b8bf849fcfc9c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="521708"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7db60a7b0b918283381b8bf849fcfc9c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="521708"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73211" title="Codeforces Round #615 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10315:10316" 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/73274" title="Разбор Codeforces Round #615 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="11508:11509" 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/1294">Задачи</a></li> <li><a href="/contest/1294/submit">Отослать</a></li> <li><a href="/contest/1294/my">Мои посылки</a></li> <li><a href="/contest/1294/status">Статус</a></li> <li><a href="/contest/1294/hacks">Взломы</a></li> <li><a href="/contest/1294/standings">Положение</a></li> <li><a href="/contest/1294/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ca099ac45d8fc331d0e7d507b29200da73faa9fd"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Сбор посылок</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На складе есть робот и $$$n$$$ посылок, которые он хочет собрать. Склад можно представить в виде координатной сетки. Изначально робот находится в точке $$$(0, 0)$$$. $$$i$$$-я посылка находится в точке $$$(x_i, y_i)$$$. Гарантируется, что в одной точке не могут находиться две посылки. Также гарантируется, что в точке $$$(0, 0)$$$ посылки нет.</p><p>Робот наполовину сломан и может передвигаться только вверх ('<span class="tex-font-style-tt">U</span>') и вправо ('<span class="tex-font-style-tt">R</span>'). Другими словами, за один шаг робот может переместиться из точки $$$(x, y)$$$ в точку ($$$x + 1, y$$$) или в точку $$$(x, y + 1)$$$. Как сказано выше, робот хочет собрать все $$$n$$$ посылок (<span class="tex-font-style-bf">в любом порядке</span>). Он хочет сделать это за минимально возможное число шагов. Если существует несколько подходящих последовательностей шагов, робот хочет выбрать лексикографически минимальный путь.</p><p>Строка $$$s$$$ длины $$$n$$$ лексикографически меньше, чем строка $$$t$$$ длины $$$n$$$ если существует такой индекс $$$1 \le j \le n$$$, что для всех $$$i$$$ от $$$1$$$ до $$$j-1$$$ $$$s_i = t_i$$$ и $$$s_j &lt; t_j$$$. Это обычное сравнение строк, например, в словаре строки расположены в лексикографическом порядке. Большинство языков программирования сравнивают строки именно так.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 1000$$$) — количество посылок на складе.</p><p>Следующие $$$n$$$ строк содержат описания посылок. $$$i$$$-я посылка задана в виде двух целых чисел $$$x_i$$$ и $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) — $$$x$$$-координаты посылки и $$$y$$$-координаты посылки.</p><p>Гарантируется, что в каждой точке находится не более одной посылки. Также гарантируется, что в точке $$$(0, 0)$$$ посылки нет.</p><p>Сумма $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$1000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите ответ.</p><p>Если невозможно собрать все $$$n$$$ посылок в каком-либо порядке, стартуя из точки ($$$0,0$$$), выведите «<span class="tex-font-style-tt">NO</span>» первой строкой.</p><p>Иначе выведите «<span class="tex-font-style-tt">YES</span>» первой строкой. Затем выведите <span class="tex-font-style-bf">кратчайший</span> путь (строку), состоящий из символов '<span class="tex-font-style-tt">R</span>' и '<span class="tex-font-style-tt">U</span>'. Среди всех таких путей нужно выбрать лексикографически минимальный.</p><p><span class="tex-font-style-bf">Заметьте, что в этой задаче «<span class="tex-font-style-tt">YES</span>» и «<span class="tex-font-style-tt">NO</span>» могут быть выведены только в верхнем регистре, то есть «<span class="tex-font-style-tt">Yes</span>», «<span class="tex-font-style-tt">no</span>» и «<span class="tex-font-style-tt">YeS</span>» не принимаются</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 1 3 1 2 3 3 5 5 4 3 2 1 0 0 1 1 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES RUUURRRRUU NO YES RRRRUUU </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора данных из указанного примера оптимальный путь <span class="tex-font-style-tt">RUUURRRRUU</span> выглядит следующим образом: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8ba8beb3d4798d0c00f093234601e29f45df5fd2.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:55: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:'812495058dd09d8a',t:'MTY5NjY2NTMyOS42MjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1200"]
1294C
1294
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$$$. Найдите три <span class="tex-font-style-bf">различных целых числа</span> $$$a, b, c$$$ таких, что $$$2 \le a, b, c$$$ и $$$a \cdot b \cdot c = n$$$ или скажите, что невозможно сделать это.</p><p>Если существует несколько подходящих ответов, вы можете вывести любой.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Следующие $$$n$$$ строк описывают наборы входных данных. $$$i$$$-й набор входных данных задан с новой строки в виде одного целого числа $$$n$$$ ($$$2 \le n \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ для каждого набора входных данных. Выведите «<span class="tex-font-style-tt">NO</span>» если невозможно представить $$$n$$$ как $$$a \cdot b \cdot c$$$ для каких-то <span class="tex-font-style-bf">различных целых чисел</span> $$$a, b, c$$$ таких, что $$$2 \le a, b, c$$$.</p><p>Иначе выведите «<span class="tex-font-style-tt">YES</span>» и <span class="tex-font-style-bf">любое</span> такое возможное представление.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 64 32 97 2 12345 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 2 4 8 NO NO NO YES 3 5 823 </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="f5a9a4f2adfc8fc51b823747e5281108"/> <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="834b33f4ae46a58d99d89ad4030429b17e8c259e"/> <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='f5a9a4f2adfc8fc51b823747e5281108'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1294%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='f5a9a4f2adfc8fc51b823747e5281108'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1294">Codeforces Round 615 (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='f5a9a4f2adfc8fc51b823747e5281108'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1294/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='f5a9a4f2adfc8fc51b823747e5281108'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="521709"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f5a9a4f2adfc8fc51b823747e5281108'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="521709"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73211" title="Codeforces Round #615 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10315:10316" 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/73274" title="Разбор Codeforces Round #615 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="11508:11509" 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/1294">Задачи</a></li> <li><a href="/contest/1294/submit">Отослать</a></li> <li><a href="/contest/1294/my">Мои посылки</a></li> <li><a href="/contest/1294/status">Статус</a></li> <li><a href="/contest/1294/hacks">Взломы</a></li> <li><a href="/contest/1294/standings">Положение</a></li> <li><a href="/contest/1294/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_955157c3f22d314f0964677b77ab87889922c024"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$. Найдите три <span class="tex-font-style-bf">различных целых числа</span> $$$a, b, c$$$ таких, что $$$2 \le a, b, c$$$ и $$$a \cdot b \cdot c = n$$$ или скажите, что невозможно сделать это.</p><p>Если существует несколько подходящих ответов, вы можете вывести любой.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Следующие $$$n$$$ строк описывают наборы входных данных. $$$i$$$-й набор входных данных задан с новой строки в виде одного целого числа $$$n$$$ ($$$2 \le n \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ для каждого набора входных данных. Выведите «<span class="tex-font-style-tt">NO</span>» если невозможно представить $$$n$$$ как $$$a \cdot b \cdot c$$$ для каких-то <span class="tex-font-style-bf">различных целых чисел</span> $$$a, b, c$$$ таких, что $$$2 \le a, b, c$$$.</p><p>Иначе выведите «<span class="tex-font-style-tt">YES</span>» и <span class="tex-font-style-bf">любое</span> такое возможное представление.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 64 32 97 2 12345 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 2 4 8 NO NO NO YES 3 5 823 </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:55:31</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;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:'8124950de9b69d3d',t:'MTY5NjY2NTMzMS4wMzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1300"]
1294D
1294
D
ru
D. Максимизация MEX
<div class="problem-statement"><div class="header"><div class="title">D. Максимизация MEX</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Напомним, что <span class="tex-font-style-bf">MEX</span> массива — это <span class="tex-font-style-bf">минимальное неотрицательное целое число</span>, которое не представлено в массиве. Примеры:</p><ul> <li> для массива $$$[0, 0, 1, 0, 2]$$$ MEX равен $$$3$$$, потому что числа $$$0, 1$$$ и $$$2$$$ представлены в массиве, а $$$3$$$ является минимальным неотрицательным целым числом, не представленным в массиве; </li><li> для массива $$$[1, 2, 3, 4]$$$ MEX равен $$$0$$$, потому что $$$0$$$ является минимальным неотрицательным целым числом, не представленным в массиве; </li><li> для массива $$$[0, 1, 4, 3]$$$ MEX равен $$$2$$$, потому что $$$2$$$ является минимальным неотрицательным целым числом, не представленным в массиве. </li></ul><p>Вам задан пустой массив $$$a=[]$$$ (иными словами, массив нулевой длины). Также вам задано положительное целое число $$$x$$$.</p><p>Вам дано $$$q$$$ запросов. $$$j$$$-й запрос состоит из одного целого числа $$$y_j$$$, которое означает, что вы должны дописать один элемент $$$y_j$$$ в массив. Длина массива увеличивается на $$$1$$$ после каждого запроса.</p><p>За один ход вы можете выбрать любой индекс $$$i$$$ и присвоить $$$a_i := a_i + x$$$ или $$$a_i := a_i - x$$$ (т.е. увеличить или уменьшить любой элемент на $$$x$$$). Единственное ограничение — <span class="tex-font-style-bf">$$$a_i$$$ не может стать отрицательным</span>. Так как изначально массив пуст, вы можете совершать ходы только после первого запроса.</p><p>Вам нужно максимизировать <span class="tex-font-style-bf">MEX</span> (minimum excluded) массива, применив какое-то количество подобных операций (вы также можете применить несколько таких операций к одному и тому же элементу).</p><p>Вам необходимо найти ответ после каждого из $$$q$$$ запросов (то есть $$$j$$$-й ответ соответствует массиву длины $$$j$$$).</p><p><span class="tex-font-style-bf">Операции отменяются после каждого запроса. То есть массив $$$a$$$ после $$$j$$$-го запроса равен $$$[y_1, y_2, \dots, y_j]$$$.</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$q, x$$$ ($$$1 \le q, x \le 4 \cdot 10^5$$$) — количество запросов и значение числа $$$x$$$.</p><p>Следующие $$$q$$$ строк описывают запросы. $$$j$$$-й запрос состоит из целого числа $$$y_j$$$ ($$$0 \le y_j \le 10^9$$$) и означает, что вы должны дописать один элемент $$$y_j$$$ в массив.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ на изначальную задачу после каждого запроса — для запроса $$$j$$$ выведите максимальное значение <span class="tex-font-style-bf">MEX</span> после первых $$$j$$$ запросов. Стоит заметить, что запроса зависимы (массив меняется после каждого запроса), но операции между запросами независимы.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 3 0 1 2 2 0 0 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 3 4 4 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере:</p><ul> <li> После первого запроса массив равен $$$a=[0]$$$: нет необходимости применять операции, максимально возможный MEX равен $$$1$$$. </li><li> После второго запроса массив равен $$$a=[0, 1]$$$: нет необходимости применять операции, максимально возможный MEX равен $$$2$$$. </li><li> После третьего запроса массив равен $$$a=[0, 1, 2]$$$: нет необходимости применять операции, максимально возможный MEX равен $$$3$$$. </li><li> После четвертого запроса массив равен $$$a=[0, 1, 2, 2]$$$: нет необходимости применять операции, максимально возможный MEX равен $$$3$$$ (вы не можете сделать его больше, применяя операции). </li><li> После пятого запроса массив равен $$$a=[0, 1, 2, 2, 0]$$$: вы можете совершить операцию $$$a[4] := a[4] + 3 = 3$$$. Массив изменится и станет равен $$$a=[0, 1, 2, 2, 3]$$$. Теперь MEX является максимально возможным и равен $$$4$$$. </li><li> После шестого запроса массив равен $$$a=[0, 1, 2, 2, 0, 0]$$$: вы можете совершить операцию $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$. Массив изменится и станет равен $$$a=[0, 1, 2, 2, 3, 0]$$$. Теперь MEX является максимально возможным и равен $$$4$$$. </li><li> После седьмого запроса массив равен $$$a=[0, 1, 2, 2, 0, 0, 10]$$$. Вы можете совершить следующие операции: <ul> <li> $$$a[3] := a[3] + 3 = 2 + 3 = 5$$$, </li><li> $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$, </li><li> $$$a[5] := a[5] + 3 = 0 + 3 = 3$$$, </li><li> $$$a[5] := a[5] + 3 = 3 + 3 = 6$$$, </li><li> $$$a[6] := a[6] - 3 = 10 - 3 = 7$$$, </li><li> $$$a[6] := a[6] - 3 = 7 - 3 = 4$$$. </li></ul> Результирующий массив будет равен $$$a=[0, 1, 2, 5, 3, 6, 4]$$$. Теперь MEX является максимально возможным и равен $$$7$$$. </li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="f398ace18155f567ed588ec6c4d4ba18"/> <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="834b33f4ae46a58d99d89ad4030429b17e8c259e"/> <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='f398ace18155f567ed588ec6c4d4ba18'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1294%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='f398ace18155f567ed588ec6c4d4ba18'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1294">Codeforces Round 615 (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='f398ace18155f567ed588ec6c4d4ba18'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1294/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='f398ace18155f567ed588ec6c4d4ba18'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="521710"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f398ace18155f567ed588ec6c4d4ba18'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="521710"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73211" title="Codeforces Round #615 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10315:10316" 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/73274" title="Разбор Codeforces Round #615 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="11508:11509" 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/1294">Задачи</a></li> <li><a href="/contest/1294/submit">Отослать</a></li> <li><a href="/contest/1294/my">Мои посылки</a></li> <li><a href="/contest/1294/status">Статус</a></li> <li><a href="/contest/1294/hacks">Взломы</a></li> <li><a href="/contest/1294/standings">Положение</a></li> <li><a href="/contest/1294/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0e0a60a7d27a0d72a7112fd097af135e2c1a01b2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Максимизация MEX</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Напомним, что <span class="tex-font-style-bf">MEX</span> массива — это <span class="tex-font-style-bf">минимальное неотрицательное целое число</span>, которое не представлено в массиве. Примеры:</p><ul> <li> для массива $$$[0, 0, 1, 0, 2]$$$ MEX равен $$$3$$$, потому что числа $$$0, 1$$$ и $$$2$$$ представлены в массиве, а $$$3$$$ является минимальным неотрицательным целым числом, не представленным в массиве; </li><li> для массива $$$[1, 2, 3, 4]$$$ MEX равен $$$0$$$, потому что $$$0$$$ является минимальным неотрицательным целым числом, не представленным в массиве; </li><li> для массива $$$[0, 1, 4, 3]$$$ MEX равен $$$2$$$, потому что $$$2$$$ является минимальным неотрицательным целым числом, не представленным в массиве. </li></ul><p>Вам задан пустой массив $$$a=[]$$$ (иными словами, массив нулевой длины). Также вам задано положительное целое число $$$x$$$.</p><p>Вам дано $$$q$$$ запросов. $$$j$$$-й запрос состоит из одного целого числа $$$y_j$$$, которое означает, что вы должны дописать один элемент $$$y_j$$$ в массив. Длина массива увеличивается на $$$1$$$ после каждого запроса.</p><p>За один ход вы можете выбрать любой индекс $$$i$$$ и присвоить $$$a_i := a_i + x$$$ или $$$a_i := a_i - x$$$ (т.е. увеличить или уменьшить любой элемент на $$$x$$$). Единственное ограничение — <span class="tex-font-style-bf">$$$a_i$$$ не может стать отрицательным</span>. Так как изначально массив пуст, вы можете совершать ходы только после первого запроса.</p><p>Вам нужно максимизировать <span class="tex-font-style-bf">MEX</span> (minimum excluded) массива, применив какое-то количество подобных операций (вы также можете применить несколько таких операций к одному и тому же элементу).</p><p>Вам необходимо найти ответ после каждого из $$$q$$$ запросов (то есть $$$j$$$-й ответ соответствует массиву длины $$$j$$$).</p><p><span class="tex-font-style-bf">Операции отменяются после каждого запроса. То есть массив $$$a$$$ после $$$j$$$-го запроса равен $$$[y_1, y_2, \dots, y_j]$$$.</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$q, x$$$ ($$$1 \le q, x \le 4 \cdot 10^5$$$) — количество запросов и значение числа $$$x$$$.</p><p>Следующие $$$q$$$ строк описывают запросы. $$$j$$$-й запрос состоит из целого числа $$$y_j$$$ ($$$0 \le y_j \le 10^9$$$) и означает, что вы должны дописать один элемент $$$y_j$$$ в массив.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ на изначальную задачу после каждого запроса — для запроса $$$j$$$ выведите максимальное значение <span class="tex-font-style-bf">MEX</span> после первых $$$j$$$ запросов. Стоит заметить, что запроса зависимы (массив меняется после каждого запроса), но операции между запросами независимы.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 3 0 1 2 2 0 0 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 3 4 4 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере:</p><ul> <li> После первого запроса массив равен $$$a=[0]$$$: нет необходимости применять операции, максимально возможный MEX равен $$$1$$$. </li><li> После второго запроса массив равен $$$a=[0, 1]$$$: нет необходимости применять операции, максимально возможный MEX равен $$$2$$$. </li><li> После третьего запроса массив равен $$$a=[0, 1, 2]$$$: нет необходимости применять операции, максимально возможный MEX равен $$$3$$$. </li><li> После четвертого запроса массив равен $$$a=[0, 1, 2, 2]$$$: нет необходимости применять операции, максимально возможный MEX равен $$$3$$$ (вы не можете сделать его больше, применяя операции). </li><li> После пятого запроса массив равен $$$a=[0, 1, 2, 2, 0]$$$: вы можете совершить операцию $$$a[4] := a[4] + 3 = 3$$$. Массив изменится и станет равен $$$a=[0, 1, 2, 2, 3]$$$. Теперь MEX является максимально возможным и равен $$$4$$$. </li><li> После шестого запроса массив равен $$$a=[0, 1, 2, 2, 0, 0]$$$: вы можете совершить операцию $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$. Массив изменится и станет равен $$$a=[0, 1, 2, 2, 3, 0]$$$. Теперь MEX является максимально возможным и равен $$$4$$$. </li><li> После седьмого запроса массив равен $$$a=[0, 1, 2, 2, 0, 0, 10]$$$. Вы можете совершить следующие операции: <ul> <li> $$$a[3] := a[3] + 3 = 2 + 3 = 5$$$, </li><li> $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$, </li><li> $$$a[5] := a[5] + 3 = 0 + 3 = 3$$$, </li><li> $$$a[5] := a[5] + 3 = 3 + 3 = 6$$$, </li><li> $$$a[6] := a[6] - 3 = 10 - 3 = 7$$$, </li><li> $$$a[6] := a[6] - 3 = 7 - 3 = 4$$$. </li></ul> Результирующий массив будет равен $$$a=[0, 1, 2, 5, 3, 6, 4]$$$. Теперь MEX является максимально возможным и равен $$$7$$$. </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:55: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:'81249516a95f9d63',t:'MTY5NjY2NTMzMi4zNzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1600"]
1294E
1294
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 \times m$$$, состоящая из целых чисел от $$$1$$$ до $$$2 \cdot 10^5$$$. За один ход вы можете:</p><ul> <li> выбрать <span class="tex-font-style-bf">любой элемент</span> матрицы и изменить его значение на <span class="tex-font-style-bf">любое</span> целое число от $$$1$$$ до $$$n \cdot m$$$, включительно; </li><li> взять <span class="tex-font-style-bf">любой столбец</span> и сдвинуть его на одну клетку вверх циклически (смотрите пример такого циклического сдвига ниже). </li></ul><p>Циклический сдвиг — это операция, в которой выбирается некоторое $$$j$$$ ($$$1 \le j \le m$$$) и присваивается $$$a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \dots, a_{n, j} := a_{1, j}$$$ <span class="tex-font-style-bf">одновременно</span>.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/874a76a681a525102f53f73c046f306bcc2f1b6d.png" style="max-width: 100.0%;max-height: 100.0%;"/> Пример циклического сдвига первого столбца </center><p>Вы хотите определить минимальное количество шагов, за которое можно привести матрицу к подобному виду:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/886b8c37bc9a14c44d2c736abb7a98b18d00de3d.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Другими словами, ваша цель — получить матрицу, в которой $$$a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$$$ (i.e. $$$a_{i, j} = (i - 1) \cdot m + j$$$) за <span class="tex-font-style-bf">минимальное число шагов</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5, n \cdot m \le 2 \cdot 10^5$$$) — размер матрицы.</p><p>Следующие $$$n$$$ строк содержат по $$$m$$$ целых чисел в каждой. Число в строке $$$i$$$ на позиции $$$j$$$ равно $$$a_{i, j}$$$ ($$$1 \le a_{i, j} \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное число шагов, необходимое, чтобы получить матрицу, в которой $$$a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$$$ ($$$a_{i, j} = (i - 1)m + 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 3 3 2 1 1 2 3 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 3 4 5 6 7 8 9 10 11 12 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 6 3 4 5 10 7 8 9 2 11 12 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере можно присвоить $$$a_{1, 1} := 7, a_{1, 2} := 8$$$ и $$$a_{1, 3} := 9$$$, а затем циклически сдвинуть первый, втрой и третий столбцы, таким образом, ответ равен $$$6$$$. Можно показать, что лучшего результата достигнуть невозможно.</p><p>Во втором тестовом примере матрица уже является хорошей, поэтому ответ равен $$$0$$$.</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="54b4dcf59f894613998a97ed625d877e"/> <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="834b33f4ae46a58d99d89ad4030429b17e8c259e"/> <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='54b4dcf59f894613998a97ed625d877e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1294%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='54b4dcf59f894613998a97ed625d877e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1294">Codeforces Round 615 (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='54b4dcf59f894613998a97ed625d877e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1294/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='54b4dcf59f894613998a97ed625d877e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="521711"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='54b4dcf59f894613998a97ed625d877e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="521711"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73211" title="Codeforces Round #615 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10315:10316" 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/73274" title="Разбор Codeforces Round #615 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="11508:11509" 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/1294">Задачи</a></li> <li><a href="/contest/1294/submit">Отослать</a></li> <li><a href="/contest/1294/my">Мои посылки</a></li> <li><a href="/contest/1294/status">Статус</a></li> <li><a href="/contest/1294/hacks">Взломы</a></li> <li><a href="/contest/1294/standings">Положение</a></li> <li><a href="/contest/1294/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_66271f393066f8167b8ad01f3f821f936ee76c4d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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 \times m$$$, состоящая из целых чисел от $$$1$$$ до $$$2 \cdot 10^5$$$. За один ход вы можете:</p><ul> <li> выбрать <span class="tex-font-style-bf">любой элемент</span> матрицы и изменить его значение на <span class="tex-font-style-bf">любое</span> целое число от $$$1$$$ до $$$n \cdot m$$$, включительно; </li><li> взять <span class="tex-font-style-bf">любой столбец</span> и сдвинуть его на одну клетку вверх циклически (смотрите пример такого циклического сдвига ниже). </li></ul><p>Циклический сдвиг — это операция, в которой выбирается некоторое $$$j$$$ ($$$1 \le j \le m$$$) и присваивается $$$a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \dots, a_{n, j} := a_{1, j}$$$ <span class="tex-font-style-bf">одновременно</span>.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/874a76a681a525102f53f73c046f306bcc2f1b6d.png" style="max-width: 100.0%;max-height: 100.0%;" /> Пример циклического сдвига первого столбца </center><p>Вы хотите определить минимальное количество шагов, за которое можно привести матрицу к подобному виду:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/886b8c37bc9a14c44d2c736abb7a98b18d00de3d.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Другими словами, ваша цель — получить матрицу, в которой $$$a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$$$ (i.e. $$$a_{i, j} = (i - 1) \cdot m + j$$$) за <span class="tex-font-style-bf">минимальное число шагов</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5, n \cdot m \le 2 \cdot 10^5$$$) — размер матрицы.</p><p>Следующие $$$n$$$ строк содержат по $$$m$$$ целых чисел в каждой. Число в строке $$$i$$$ на позиции $$$j$$$ равно $$$a_{i, j}$$$ ($$$1 \le a_{i, j} \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное число шагов, необходимое, чтобы получить матрицу, в которой $$$a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$$$ ($$$a_{i, j} = (i - 1)m + 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 3 3 2 1 1 2 3 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 3 4 5 6 7 8 9 10 11 12 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 6 3 4 5 10 7 8 9 2 11 12 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере можно присвоить $$$a_{1, 1} := 7, a_{1, 2} := 8$$$ и $$$a_{1, 3} := 9$$$, а затем циклически сдвинуть первый, втрой и третий столбцы, таким образом, ответ равен $$$6$$$. Можно показать, что лучшего результата достигнуть невозможно.</p><p>Во втором тестовом примере матрица уже является хорошей, поэтому ответ равен $$$0$$$.</p><p>В третьем тестовом примере достаточно дважды циклически сдвинуть второй столбец, чтобы получить хорошую матрицу, поэтому ответ равен $$$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:55: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:'8124951f09d59d3f',t:'MTY5NjY2NTMzMy43MTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1900"]
1294F
1294
F
ru
F. Три пути в дереве
<div class="problem-statement"><div class="header"><div class="title">F. Три пути в дереве</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано невзвешенное дерево с $$$n$$$ вершинами. Напомним, что дерево — это связный неориентированный граф без циклов.</p><p>Ваша задача — выбрать <span class="tex-font-style-bf">три различных</span> вершины $$$a, b, c$$$ в этом дереве таких, что количество ребер, принадлежащих <span class="tex-font-style-bf">как минимум</span> одному из простых путей между $$$a$$$ и $$$b$$$, $$$b$$$ и $$$c$$$, или $$$a$$$ и $$$c$$$, максимально. Обратите внимание на примечания для лучшего понимания.</p><p>Простой путь — это путь, который посещает каждую вершину не более одного раза.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — количество вершин в дереве. </p><p>Следующая $$$n - 1$$$ строка описывает ребра дерева в виде $$$a_i, b_i$$$ ($$$1 \le a_i$$$, $$$b_i \le n$$$, $$$a_i \ne b_i$$$). Гарантируется, что заданный граф является деревом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Первой строкой выведите одно целое число $$$res$$$ — максимальное количество ребер, принадлежащих <span class="tex-font-style-bf">как минимум</span> одному из простых путей между $$$a$$$ и $$$b$$$, $$$b$$$ и $$$c$$$, или $$$a$$$ и $$$c$$$.</p><p>Во второй строке выведите три целых числа $$$a, b, c$$$ таких, что $$$1 \le a, b, c \le n$$$ и $$$a \ne, b \ne c, a \ne c$$$.</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> 8 1 2 2 3 3 4 4 5 4 6 3 7 3 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 1 8 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Изображение, соответствующее первому примеру (и <span class="tex-font-style-bf">другой правильный ответ</span>):</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/a14350f33ff1d0a53f558a037dbaf779e81c1ee9.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Если выбрать вершины $$$1, 5, 6$$$, то путь между вершинами $$$1$$$ и $$$5$$$ состоит из ребер $$$(1, 2), (2, 3), (3, 4), (4, 5)$$$, путь между $$$1$$$ и $$$6$$$ состоит из ребер $$$(1, 2), (2, 3), (3, 4), (4, 6)$$$ и путь между $$$5$$$ и $$$6$$$ состоит из ребер $$$(4, 5), (4, 6)$$$. Объединение этих путей — $$$(1, 2), (2, 3), (3, 4), (4, 5), (4, 6)$$$, следовательно, ответ — $$$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="d380c55343ab9c9eff39566b540edd1a"/> <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="834b33f4ae46a58d99d89ad4030429b17e8c259e"/> <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='d380c55343ab9c9eff39566b540edd1a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1294%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='d380c55343ab9c9eff39566b540edd1a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1294">Codeforces Round 615 (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='d380c55343ab9c9eff39566b540edd1a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1294/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='d380c55343ab9c9eff39566b540edd1a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="521712"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d380c55343ab9c9eff39566b540edd1a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="521712"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73211" title="Codeforces Round #615 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10315:10316" 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/73274" title="Разбор Codeforces Round #615 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="11508:11509" 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/1294">Задачи</a></li> <li><a href="/contest/1294/submit">Отослать</a></li> <li><a href="/contest/1294/my">Мои посылки</a></li> <li><a href="/contest/1294/status">Статус</a></li> <li><a href="/contest/1294/hacks">Взломы</a></li> <li><a href="/contest/1294/standings">Положение</a></li> <li><a href="/contest/1294/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b8068688a4751f8b3758cfdbe6c3d4e5a8e6d619"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Три пути в дереве</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано невзвешенное дерево с $$$n$$$ вершинами. Напомним, что дерево — это связный неориентированный граф без циклов.</p><p>Ваша задача — выбрать <span class="tex-font-style-bf">три различных</span> вершины $$$a, b, c$$$ в этом дереве таких, что количество ребер, принадлежащих <span class="tex-font-style-bf">как минимум</span> одному из простых путей между $$$a$$$ и $$$b$$$, $$$b$$$ и $$$c$$$, или $$$a$$$ и $$$c$$$, максимально. Обратите внимание на примечания для лучшего понимания.</p><p>Простой путь — это путь, который посещает каждую вершину не более одного раза.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — количество вершин в дереве. </p><p>Следующая $$$n - 1$$$ строка описывает ребра дерева в виде $$$a_i, b_i$$$ ($$$1 \le a_i$$$, $$$b_i \le n$$$, $$$a_i \ne b_i$$$). Гарантируется, что заданный граф является деревом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Первой строкой выведите одно целое число $$$res$$$ — максимальное количество ребер, принадлежащих <span class="tex-font-style-bf">как минимум</span> одному из простых путей между $$$a$$$ и $$$b$$$, $$$b$$$ и $$$c$$$, или $$$a$$$ и $$$c$$$.</p><p>Во второй строке выведите три целых числа $$$a, b, c$$$ таких, что $$$1 \le a, b, c \le n$$$ и $$$a \ne, b \ne c, a \ne c$$$.</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> 8 1 2 2 3 3 4 4 5 4 6 3 7 3 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 1 8 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Изображение, соответствующее первому примеру (и <span class="tex-font-style-bf">другой правильный ответ</span>):</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/a14350f33ff1d0a53f558a037dbaf779e81c1ee9.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Если выбрать вершины $$$1, 5, 6$$$, то путь между вершинами $$$1$$$ и $$$5$$$ состоит из ребер $$$(1, 2), (2, 3), (3, 4), (4, 5)$$$, путь между $$$1$$$ и $$$6$$$ состоит из ребер $$$(1, 2), (2, 3), (3, 4), (4, 6)$$$ и путь между $$$5$$$ и $$$6$$$ состоит из ребер $$$(4, 5), (4, 6)$$$. Объединение этих путей — $$$(1, 2), (2, 3), (3, 4), (4, 5), (4, 6)$$$, следовательно, ответ — $$$5$$$. Можно показать, что лучшего ответа не существует.</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:55: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:'812495276a6e00a1',t:'MTY5NjY2NTMzNS4wNTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2000"]
1295A
1295
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>У вас есть большое электронное табло, на котором можно отобразить до $$$998244353$$$ десятичных цифр. Цифры отображаются таким же образом, как на электронных часах: каждая позиция для цифры состоит из $$$7$$$ сегментов, которые могут быть включены или выключены, чтобы отображать различные цифры. На картинке показано, как изображаются все $$$10$$$ десятичных цифр:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/39cedf07ce9ef18d7ec074f319640a9857b9f8cb.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Как вы можете заметить, разные цифры могут потребовать включения разного количества сегментов для их отображения. Например, если вы хотите отобразить $$$1$$$, надо включить $$$2$$$ сегмента, а если вы хотите отобразить $$$8$$$, все $$$7$$$ сегментов на некоторой позиции должны быть включены.</p><p>Вы хотите отобразить очень большое целое число на экране. К сожалению, из-за бага нельзя включить более $$$n$$$ сегментов одновременно. Поэтому вы хотите узнать, какое наибольшее целое число можно отобразить, включив не более $$$n$$$ сегментов.</p><p>Ваша программа должна уметь обрабатывать $$$t$$$ наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Затем следуют сами наборы входных данных, каждый из которых состоит из одной строки, содержащей единственное число $$$n$$$ ($$$2 \le n \le 10^5$$$) — максимальное количество включенных сегментов в соответствующем наборе входных данных.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите наибольшее целое число, которое можно отобразить, включив не более $$$n$$$ сегментов на экране. Обратите внимание, что ответ может не помещаться в стандартные $$$32$$$-битные или $$$64$$$-битные целочисленные типы данных.</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 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 11 </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="8af4018d16b8a65d2525a533d7279cce"/> <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="07d8459840620e17d4825a421190eb8553c0b301"/> <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='8af4018d16b8a65d2525a533d7279cce'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1295%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='8af4018d16b8a65d2525a533d7279cce'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1295">Educational Codeforces Round 81 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='8af4018d16b8a65d2525a533d7279cce'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1295/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='8af4018d16b8a65d2525a533d7279cce'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="526700"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8af4018d16b8a65d2525a533d7279cce'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="526700"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73413" title="Educational Codeforces Round 81" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10342" resourceName="Educational Codeforces Round 81" resourceManual="true" src="//codeforces.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/73467" title="Разбор Educational Codeforces Round 81" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10337:10338" 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/1295">Задачи</a></li> <li><a href="/contest/1295/submit">Отослать</a></li> <li><a href="/contest/1295/my">Мои посылки</a></li> <li><a href="/contest/1295/status">Статус</a></li> <li><a href="/contest/1295/hacks">Взломы</a></li> <li><a href="/contest/1295/standings">Положение</a></li> <li><a href="/contest/1295/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_021acb02fc042c3fe9d912ad80858083b10a667c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>У вас есть большое электронное табло, на котором можно отобразить до $$$998244353$$$ десятичных цифр. Цифры отображаются таким же образом, как на электронных часах: каждая позиция для цифры состоит из $$$7$$$ сегментов, которые могут быть включены или выключены, чтобы отображать различные цифры. На картинке показано, как изображаются все $$$10$$$ десятичных цифр:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/39cedf07ce9ef18d7ec074f319640a9857b9f8cb.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Как вы можете заметить, разные цифры могут потребовать включения разного количества сегментов для их отображения. Например, если вы хотите отобразить $$$1$$$, надо включить $$$2$$$ сегмента, а если вы хотите отобразить $$$8$$$, все $$$7$$$ сегментов на некоторой позиции должны быть включены.</p><p>Вы хотите отобразить очень большое целое число на экране. К сожалению, из-за бага нельзя включить более $$$n$$$ сегментов одновременно. Поэтому вы хотите узнать, какое наибольшее целое число можно отобразить, включив не более $$$n$$$ сегментов.</p><p>Ваша программа должна уметь обрабатывать $$$t$$$ наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Затем следуют сами наборы входных данных, каждый из которых состоит из одной строки, содержащей единственное число $$$n$$$ ($$$2 \le n \le 10^5$$$) — максимальное количество включенных сегментов в соответствующем наборе входных данных.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите наибольшее целое число, которое можно отобразить, включив не более $$$n$$$ сегментов на экране. Обратите внимание, что ответ может не помещаться в стандартные $$$32$$$-битные или $$$64$$$-битные целочисленные типы данных.</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 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 11 </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:55: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:'8124952fbda13a65',t:'MTY5NjY2NTMzNi40NDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*900"]
1295B
1295
B
ru
B. Бесконечные префиксы
<div class="problem-statement"><div class="header"><div class="title">B. Бесконечные префиксы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана строка $$$s$$$ длины $$$n$$$, состоящая только из <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>. Построим бесконечную строку $$$t$$$ как конкатенацию бесконечного числа строк $$$s$$$, или $$$t = ssss \dots$$$ Например, если $$$s =$$$ <span class="tex-font-style-tt">10010</span>, то $$$t =$$$ <span class="tex-font-style-tt">100101001010010</span>...</p><p>Посчитайте количество префиксов $$$t$$$ с <span class="tex-font-style-it">балансом</span> равным $$$x$$$. Баланс строки $$$q$$$ равен $$$cnt_{0, q} - cnt_{1, q}$$$, где $$$cnt_{0, q}$$$ — это количество вхождений <span class="tex-font-style-tt">0</span> в $$$q$$$, а $$$cnt_{1, q}$$$ — количество вхождений <span class="tex-font-style-tt">1</span> в $$$q$$$. Количество таких префиксов может быть бесконечно: в таком случае, вы должны определить это.</p><p>Префикс — строка, состоящая из нескольких первых букв заданной строки, без изменения их порядка. Пустой префикс тоже является префиксом. Например, у строки «abcd» пять префиксов: пустая строка, «a», «ab», «abc» и «abcd».</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$T$$$ ($$$1 \le T \le 100$$$) — количество наборов входных данных.</p><p>В следующих $$$2T$$$ строках заданы описания наборов входных данных — по две строки на набор. В первой строке задано два целых числа $$$n$$$ и $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) — длина строки $$$s$$$ и желаемый баланс, соответственно.</p><p>Во второй строке задана бинарная строка $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$).</p><p>Гарантируется, что общая сумма $$$n$$$ не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$T$$$ чисел — по одному на набор входных данных. Для каждого набора выведите количество префиксов или $$$-1$$$, если таких префиксов бесконечное количество.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 6 10 010010 5 3 10101 1 0 0 2 0 01 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 0 1 -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе есть 3 хороших префикса строки $$$t$$$: длины $$$28$$$, $$$30$$$ и $$$32$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="4c310b6aaf82a91f26c0e7f5ce6b7853"/> <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="07d8459840620e17d4825a421190eb8553c0b301"/> <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='4c310b6aaf82a91f26c0e7f5ce6b7853'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1295%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='4c310b6aaf82a91f26c0e7f5ce6b7853'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1295">Educational Codeforces Round 81 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='4c310b6aaf82a91f26c0e7f5ce6b7853'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1295/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1700 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4c310b6aaf82a91f26c0e7f5ce6b7853'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="526701"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4c310b6aaf82a91f26c0e7f5ce6b7853'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="526701"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73413" title="Educational Codeforces Round 81" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10342" resourceName="Educational Codeforces Round 81" resourceManual="true" src="//codeforces.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/73467" title="Разбор Educational Codeforces Round 81" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10337:10338" 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/1295">Задачи</a></li> <li><a href="/contest/1295/submit">Отослать</a></li> <li><a href="/contest/1295/my">Мои посылки</a></li> <li><a href="/contest/1295/status">Статус</a></li> <li><a href="/contest/1295/hacks">Взломы</a></li> <li><a href="/contest/1295/standings">Положение</a></li> <li><a href="/contest/1295/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f6b69ebf1bc3cb1e3080f9ec40ca40f380e34914"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Бесконечные префиксы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана строка $$$s$$$ длины $$$n$$$, состоящая только из <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>. Построим бесконечную строку $$$t$$$ как конкатенацию бесконечного числа строк $$$s$$$, или $$$t = ssss \dots$$$ Например, если $$$s =$$$ <span class="tex-font-style-tt">10010</span>, то $$$t =$$$ <span class="tex-font-style-tt">100101001010010</span>...</p><p>Посчитайте количество префиксов $$$t$$$ с <span class="tex-font-style-it">балансом</span> равным $$$x$$$. Баланс строки $$$q$$$ равен $$$cnt_{0, q} - cnt_{1, q}$$$, где $$$cnt_{0, q}$$$ — это количество вхождений <span class="tex-font-style-tt">0</span> в $$$q$$$, а $$$cnt_{1, q}$$$ — количество вхождений <span class="tex-font-style-tt">1</span> в $$$q$$$. Количество таких префиксов может быть бесконечно: в таком случае, вы должны определить это.</p><p>Префикс — строка, состоящая из нескольких первых букв заданной строки, без изменения их порядка. Пустой префикс тоже является префиксом. Например, у строки «abcd» пять префиксов: пустая строка, «a», «ab», «abc» и «abcd».</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$T$$$ ($$$1 \le T \le 100$$$) — количество наборов входных данных.</p><p>В следующих $$$2T$$$ строках заданы описания наборов входных данных — по две строки на набор. В первой строке задано два целых числа $$$n$$$ и $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) — длина строки $$$s$$$ и желаемый баланс, соответственно.</p><p>Во второй строке задана бинарная строка $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$).</p><p>Гарантируется, что общая сумма $$$n$$$ не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$T$$$ чисел — по одному на набор входных данных. Для каждого набора выведите количество префиксов или $$$-1$$$, если таких префиксов бесконечное количество.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 6 10 010010 5 3 10101 1 0 0 2 0 01 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 0 1 -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе есть 3 хороших префикса строки $$$t$$$: длины $$$28$$$, $$$30$$$ и $$$32$$$.</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:55: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:'812495386fae13b4',t:'MTY5NjY2NTMzNy43NjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0440\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"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1700"]
1295C
1295
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>Вам заданы две строки $$$s$$$ и $$$t$$$, состоящие из строчных букв латинского алфавита. Также у вас есть строка $$$z$$$, которая изначально пуста. Вы хотите, чтобы строка $$$z$$$ стала равна строке $$$t$$$. Для этого вы можете выполнять следующую операцию: добавить любую подпоследовательность строки $$$s$$$ в конец строки $$$z$$$. Подпоследовательность — это последовательность, которая получается из данной путем удаления нуля или более ее элементов. Например, если $$$z = ac$$$, $$$s = abcde$$$, вы можете превратить $$$z$$$ в следующие строки за одну операцию: </p><ol> <li> $$$z = acace$$$ (если выберете подпоследовательность $$$ace$$$); </li><li> $$$z = acbcd$$$ (если выберете подпоследовательность $$$bcd$$$); </li><li> $$$z = acbce$$$ (если выберете подпоследовательность $$$bce$$$). </li></ol><p>Обратите внимание, что строка $$$s$$$ не меняется после операций.</p><p>Посчитайте минимальное количество операций, необходимое для того, чтобы превратить строку $$$z$$$ в строку $$$t$$$. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное число $$$T$$$ ($$$1 \le T \le 100$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит строку $$$s$$$ ($$$1 \le |s| \le 10^5$$$), состоящую из строчных букв латинского алфавита.</p><p>Вторая строка каждого набора входных данных содержит строку $$$t$$$ ($$$1 \le |t| \le 10^5$$$), состоящую из строчных букв латинского алфавита.</p><p>Гарантируется, что суммарная длина строк $$$s$$$ и $$$t$$$ во входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите одно число — минимальное количество операций, необходимое для того, чтобы превратить строку $$$z$$$ в строку $$$t$$$. Если это невозможно выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 aabce ace abacaba aax ty yyt </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 -1 3 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="74136281f76edcd80a118da036dec7a5"/> <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="07d8459840620e17d4825a421190eb8553c0b301"/> <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='74136281f76edcd80a118da036dec7a5'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1295%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='74136281f76edcd80a118da036dec7a5'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1295">Educational Codeforces Round 81 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='74136281f76edcd80a118da036dec7a5'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1295/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1600 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='74136281f76edcd80a118da036dec7a5'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="526702"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='74136281f76edcd80a118da036dec7a5'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="526702"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/73413" title="Educational Codeforces Round 81" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10342" resourceName="Educational Codeforces Round 81" resourceManual="true" src="//codeforces.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/73467" title="Разбор Educational Codeforces Round 81" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10337:10338" 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/1295">Задачи</a></li> <li><a href="/contest/1295/submit">Отослать</a></li> <li><a href="/contest/1295/my">Мои посылки</a></li> <li><a href="/contest/1295/status">Статус</a></li> <li><a href="/contest/1295/hacks">Взломы</a></li> <li><a href="/contest/1295/standings">Положение</a></li> <li><a href="/contest/1295/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_870b181c34b1026fcfb6445c73b560485ad5a523"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Вам заданы две строки $$$s$$$ и $$$t$$$, состоящие из строчных букв латинского алфавита. Также у вас есть строка $$$z$$$, которая изначально пуста. Вы хотите, чтобы строка $$$z$$$ стала равна строке $$$t$$$. Для этого вы можете выполнять следующую операцию: добавить любую подпоследовательность строки $$$s$$$ в конец строки $$$z$$$. Подпоследовательность — это последовательность, которая получается из данной путем удаления нуля или более ее элементов. Например, если $$$z = ac$$$, $$$s = abcde$$$, вы можете превратить $$$z$$$ в следующие строки за одну операцию: </p><ol> <li> $$$z = acace$$$ (если выберете подпоследовательность $$$ace$$$); </li><li> $$$z = acbcd$$$ (если выберете подпоследовательность $$$bcd$$$); </li><li> $$$z = acbce$$$ (если выберете подпоследовательность $$$bce$$$). </li></ol><p>Обратите внимание, что строка $$$s$$$ не меняется после операций.</p><p>Посчитайте минимальное количество операций, необходимое для того, чтобы превратить строку $$$z$$$ в строку $$$t$$$. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное число $$$T$$$ ($$$1 \le T \le 100$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит строку $$$s$$$ ($$$1 \le |s| \le 10^5$$$), состоящую из строчных букв латинского алфавита.</p><p>Вторая строка каждого набора входных данных содержит строку $$$t$$$ ($$$1 \le |t| \le 10^5$$$), состоящую из строчных букв латинского алфавита.</p><p>Гарантируется, что суммарная длина строк $$$s$$$ и $$$t$$$ во входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите одно число — минимальное количество операций, необходимое для того, чтобы превратить строку $$$z$$$ в строку $$$t$$$. Если это невозможно выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 aabce ace abacaba aax ty yyt </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 -1 3 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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:55: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:'81249540cbd375bb',t:'MTY5NjY2NTMzOS4xMDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1600"]